Ivan C Ivan C - 1 year ago 72
Java Question

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()))

Am I missing something? The list is not sorting.

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)

Answer Source

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().

You've just missed to assign the result :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download