using java streams to rank data in an array list

java 8 sort list of objects descending
java 8 sort list of strings
java stream sort by date
java 8 sort list of objects by multiple attributes
java list sort
sort list of map in java 8
collections.sort java 8
sort list of list java

I have an ArrayList containing strings for example list 1 may be a list of names:

Bill, Bill, Bill, Henry, Sue, Sue

How do I use java streams to return the array as follows in ranked order (by occurrence)?

Bill, Bill, Bill, Sue, Sue, Henry

It would also be great to know how to display the final ranking of Bill, Sue, Henry. I have the following code:

System.out.println(
   name.stream()
       .sorted(Comparator.comparing(a->a))
       .collect(Collectors.toList())
);

where name is the array. It works fine and arranges the array according to name but I also want to introduce ranking.

First it's a little bit unclear what you actually want to achieve: a List<List<String>> or List<String[]> or a String[]...

One one hand you want Bill, Bill, Bill, Sue, Sue, Henry, but if your list is {Bill, Bill, Bill, Sue, Henry, Henry}; {Bill, Gene, Sue} what would your result be in such case? A single String[] or .... what exactly? You also mention that how to display the final ranking of Bill, Sue, Henry, which obviously means something else entirely...

In any case:

Shmosel solution in comments is indeed very nice! (but assume two things, that your list is editable, thus you can sort it and that you want a sorted List as opposed to an array). And you can't refactor that to a single stream operation that returns an array, because that would mean consuming the stream twice... which you can't.

You can do it via two operations:

List<String> flat = all.stream()
            .flatMap(List::stream)
            .collect(Collectors.toList());

    String[] result = flat.stream()
            .sorted(Comparator.comparing(x -> Collections.frequency(flat, x)).reversed())
            .toArray(String[]::new);

This will for the input that I gave above will be:

[Bill, Bill, Bill, Bill, Henry, Henry, Sue, Sue, Gene]

If you want to sort each list, then you could use:

 List<List<String>> res = all.stream()
            .map(x -> x.stream()
                    .sorted(Comparator.comparing(y -> Collections.frequency(x, y)).reversed())
                    .collect(Collectors.toList()))
            .collect(Collectors.toList());

And the result will be:

 [[Bill, Bill, Bill, Henry, Henry, Sue], [Bill, Gene, Sue]]

Computing a ranking with Java 8 Stream API, The typical ranking, as shown above, is a list of items preceded by their relative ranking value. using a supporting map data structure upon which the stream Indeed, I find I can replace an ArrayList with a Stack in further: If you cannot use explicit sort, use implicit one: loop through array and initialise TreeMap rankMap, where Rank = {int rank = 0;}, by putting into map key = input[I] and value = default new Rank instance; complexity ≈ O(N*log(N)); memory ≈ O(N) S = rankMap.size();

This is not an answer on my own, i will just refactor shmosel's comment to take into account Eugene's remarks.

final List<String> names = <your names here>;

final Map<String, Long> namesByOccurence = names.stream()
    .collect(Collectors.groupingBy(
        Function.identity(),
        Collectors.counting()
    ));

final Comparator<String> byOccurrence = Comparator.comparing(namesByOccurence::get);

final String[] res = names.stream()
    .sorted(byOccurrence.reversed())
    .toArray(String[]::new);

Java 8 – How to sort list with stream.sorted() – Mkyong.com, 1.1 Sort a List with Comparator.naturalOrder(). package com.mkyong.sorted; import java.util.Arrays; import java.util.List; import java.util.stream. Java Stream: Arrays.stream and ArrayList stream Explore the Stream class. Call Arrays.stream and convert an ArrayList to a Stream.

Another solution is to group them, sort groups by size, then flat map:

names.stream()
        .collect(Collectors.groupingBy(x -> x))
        .values()
        .stream()
        .sorted(Comparator.comparingInt(List::size).reversed())
        .flatMap(List::stream)
        .collect(Collectors.toList())

Java 8 Lambda Comparator example for Sorting List of Custom , Without using Lambda expression: Before Java 8 we sort like this: If you are not ArrayList; import java.util.List Student("Lucy", 18, 1111)); System.out.println("​Before Sorting the student data:"); //java 8 forEach for printing the list studentlist. Converting or transforming a List and Array Objects in Java is a common task when programming. In the tutorial, We show how to do the task with lots of Java examples code by 2 approaches: Using Traditional Solution with basic Looping Using a powerful API – Java 8 Stream Map Now let’s do details with … Continue reading "How to use Java 8 Stream Map Examples with a List or Array"

here is how you could include ranking :

List<String> l = Arrays.asList("Bill", "Bill", "Bill", "Henry", "Sue", "Sue");

    Map<String, Long> m = l.stream().collect(Collectors.groupingBy(x -> x, Collectors.counting()));
    System.out.println(m);

the result is : {Sue=2, Bill=3, Henry=1}

ArrayList sort() - Sort list of objects by field, ArrayList sort() method sorts the list according to the order induced by the comparator instance. All elements in By Lokesh Gupta | Filed Under: Java ArrayList. Stream Filter Array Objects with Java 8. For using stream to filter objects in Array with Java 8, We do 2 steps: Create Stream from Array Objects. Apply the filtering in stream for Array Objects as the same way we had done with above List Objects.

Different Approaches to Sorting Elements of an ArrayList in Java , Sorting Java Arraylists: one of the most important operation on ArrayList that you will This method will sort the elements (country names) of the ArrayList using natural Imagine, the result of comparing integer values where one or both of them are negative values. Easy Fine-Grained Sorting With JDK 8. 2. Convert infinite stream to array. To convert an infinite stream into array, we must limit the stream to a finite number of elements. 2.1. Infinite stream to array to ints IntStream infiniteNumberStream = IntStream.iterate(1, i -> i+1); int[] intArray = infiniteNumberStream.limit(10) .toArray(); System.out.println(Arrays.toString(intArray));

Java 8, List in Java 8 – instead of the old Collections.sort API. 4. Basic Sorting With No Type Definitions. Step 1: Arrays.stream (arr) – In this step we call the stream method on the Arrays class passing arr as the parameter to the function this statement returns IntStream. Step 2: Arrays.stream (arr).sum () – Once we get the IntStream we can use different methods of the IntStream interface. While you go through IntStream.

Stream sorted() in Java, Remove first element from ArrayList in Java · Best Books to Learn Java for last element from ArrayList in Java · How to set Precision for Double values in Java? For ordered streams, the sort method is stable but for unordered streams,  Since Java 8, another quick and easy way to load the contents of a file into an ArrayList would be using the Java Streams API: // Using try-with-resources so the stream closes automatically try (Stream<String> stream = Files.lines (Paths.get (fileName))) { ArrayList<String> arrayList = stream.collect (Collectors.toCollection (ArrayList::new

Comments
  • Why use streams? Just name.sort(); will do it. Then print the list. (btw, an ArrayList is not an array, it’s a List)
  • names.sort(Comparator.comparing(names.stream().collect(Collectors.groupingBy(x -> x, Collectors.counting()))::get).reversed());
  • @shmosel can you add that as an answer? At first I thought it was very heavy on performance to stream the list again and again. Thought it would be better to group first, then stream the resulting map and flatMap into a list. But your use of the method reference prevents the re-streaming, and all in one statement... nice!
  • @Eugene there is no requirement for returning an array. Tho OP inconsistently says "I have an ArrayList" at the beginning but "where name is the array" at the end, however since the OP used "name.stream()" in the code example, it seems to be an ArrayList, not an array, thus allows sorting in-place. like in shmosel’s comment.
  • @ shmosel ok, I'm. I misunderstood it. I thought ::get is .get.
  • I prefer this solution as the comparator does not need to iterate the list again and again to check the frequency. Still, thumbs up to Eugene's answer for the explanation about converting between list and array.