Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list with stream.sorted() in Java

I'm interested in sorting a list from a stream. This is the code I'm using:

list.stream()     .sorted((o1, o2)->o1.getItem().getValue().compareTo(o2.getItem().getValue()))     .collect(Collectors.toList()); 

Am I missing something? The list is not sorted afterward.

It should sort the lists according to the item with the lowest value.

for (int i = 0; i < list.size(); i++) {    System.out.println("list " + (i+1));    print(list, i); } 

And the print method:

public static void print(List<List> list, int i) {     System.out.println(list.get(i).getItem().getValue()); } 
like image 842
Ivan C Avatar asked Nov 09 '16 23:11

Ivan C


People also ask

How do you sort a list object in Java 8?

Java 8 – Sorting in reverse order To sort the list in the reverse(descending) order, just change the order of the arguments like this: Sorting the list of objects of Student class by Name in reverse order: studentlist. sort((Student s1, Student s2)->s2.


1 Answers

This is not like Collections.sort() where the parameter reference gets sorted. In this case you just get a sorted stream that you need to collect and assign to another variable eventually:

List result = list.stream().sorted((o1, o2)->o1.getItem().getValue().                                    compareTo(o2.getItem().getValue())).                                    collect(Collectors.toList()); 

You've just missed to assign the result

like image 117
Jan B. Avatar answered Sep 23 '22 13:09

Jan B.