Aquí tienes unos cuantos ejemplos de como ordenar una lista con stream.sorted().
1Ordenar una lista con Comparator.naturalOrder()
package com.cdlp.sorted; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StreamApplication { public static void main(String[] args) { List < String > list = Arrays.asList("9", "A", "Z", "1", "B", "Y", "4", "a", "c"); /* List sortedList = list.stream() .sorted(Comparator.naturalOrder()) .collect(Collectors.toList()); List sortedList = list.stream() .sorted((o1,o2)-> o1.compareTo(o2)) .collect(Collectors.toList()); */ List < String > sortedList = list.stream().sorted().collect(Collectors.toList()); sortedList.forEach(System.out::println); } }
Salida:
1 4 9 A B Y Z a c
2Ordenar una lista con Comparator.reverseOrder()
package com.cdlp.sorted; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class StreamApplication { public static void main(String[] args) { List list = Arrays.asList("9", "A", "Z", "1", "B", "Y", "4", "a", "c"); /* List sortedList = list.stream() .sorted((o1,o2)-> o2.compareTo(o1)) .collect(Collectors.toList()); */ List sortedList = list.stream() .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); sortedList.forEach(System.out::println); } }
Salida:
c a Z Y B A 9 4 1
3Ordenar objetos por atributo, orden natural
package com.cdlp.sorted; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class StreamApplication { static List users = Arrays.asList( new User("C", 30), new User("D", 40), new User("A", 10), new User("B", 20), new User("E", 50)); public static void main(String[] args) { /*List sortedList = users.stream() .sorted((o1, o2) -> o1.getAge() - o2.getAge()) .collect(Collectors.toList());*/ List sortedList = users.stream() .sorted(Comparator.comparingInt(User::getAge)) .collect(Collectors.toList()); sortedList.forEach(System.out::println); } static class User { private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } } }
Salida:
User{name='A', age=10} User{name='B', age=20} User{name='C', age=30} User{name='D', age=40} User{name='E', age=50}
4Ordenar objetos por atributo, orden inverso
List sortedList = users.stream() .sorted(Comparator.comparingInt(User::getAge) .reversed()) .collect(Collectors.toList()); sortedList.forEach(System.out::println);
Salida:
User{name='E', age=50} User{name='D', age=40} User{name='C', age=30} User{name='B', age=20} User{name='A', age=10}