by @kodeazy

Java How to sort a list in descending order using streams?

Home » java » Java How to sort a list in descending order using streams?
  • In this blog we will be discussing on how to sort a list using streams in descending order.
  • To sort the list using streams we sort the list using compareTo function and we collect it as a list using collect function.
  • Below is the example syntax to sort the ArrayList.

    arrayIntegers.stream().sorted((s1,s2)->s2.compareTo(s1)).collect(Collectors.toList());
  • Below is an example code how to sort the ArrayList objects using streams in descending order.

    import java.util.*;
    import java.util.stream.Collectors;
    class ArrayListReplaceIndex{
    public static void main(String args[]){
    	List<Integer> arrayIntegers = Arrays.asList(10,30,24,60,55);
    	arrayIntegers=arrayIntegers.stream().sorted((s1,s2)->s2.compareTo(s1)).collect(Collectors.toList());
    	System.out.println("Elements before replacing"+arrayIntegers);
    	System.out.print("Elements after replacing element at second index "+arrayIntegers);
    }
    }

    Output:

    D:\java>javac ArrayListReplaceIndex.java
    D:\java>java ArrayListReplaceIndex
    Elements before replacing[60, 55, 30, 24, 10]
    Elements after replacing element at second index [60, 55, 30, 24, 10]