Monday, August 28, 2023

How to Sort List with Stream.sorted() - JAVA 8

 How to Sort List with Stream.sorted()

Here, the sorted() method also follows the natural order, as imposed by the JVM. In case of Strings, they're sorted lexicographically:

Arrays.asList("John", "Mark", "Robert", "Lucas", "Brandon").stream().sorted().forEach(System.out::println);

Running this produces:

Brandon
John
Lucas
Mark
Robert

Sorting Strings in reverse order is as simple as sorting integers in reverse order:

List<String> list = Arrays.asList("John", "Mark", "Robert", "Lucas", "Brandon");
List<String> sortedList = list.stream()
        .sorted(Collections.reverseOrder())
        .collect(Collectors.toList());
        
System.out.println(sortedList);

Let's sort them by age, first. If their age is the same, the order of insertion to the list is what defines their position in the sorted list:

List<User> userList = new ArrayList<>(Arrays.asList(
        new User("John", 33), 
        new User("Robert", 26), 
        new User("Mark", 26), 
        new User("Brandon", 42)));

List<User> sortedList = userList.stream()
        .sorted(Comparator.comparingInt(User::getAge))
        .collect(Collectors.toList());

sortedList.forEach(System.out::println);

We can easily reverse this order as well, simply by chaining the reversed() method after the comparingInt() call:

List<User> sortedList = userList.stream()
        .sorted(Comparator.comparingInt(User::getAge).reversed())
        .collect(Collectors.toList());

sortedList.forEach(System.out::println);


No comments:

Post a Comment