Java Language Sort Using Stream


Example

List<String> data = new ArrayList<>();
data.add("Sydney");
data.add("London");
data.add("New York");
data.add("Amsterdam");
data.add("Mumbai");
data.add("California");

System.out.println(data);

List<String> sortedData = data.stream().sorted().collect(Collectors.toList());

System.out.println(sortedData);

Output:

[Sydney, London, New York, Amsterdam, Mumbai, California]
[Amsterdam, California, London, Mumbai, New York, Sydney]

It's also possible to use different comparison mechanism as there is a overloaded sorted version which takes a comparator as its argument.

Also, you can use a lambda expression for sorting:

List<String> sortedData2 = data.stream().sorted((s1,s2) -> s2.compareTo(s1)).collect(Collectors.toList());

This would output [Sydney, New York, Mumbai, London, California, Amsterdam]

You can use Comparator.reverseOrder() to have a comparator that imposes the reverse of the natural ordering.

List<String> reverseSortedData = data.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());