Search code examples
javajava-8java-stream

Collectors.groupingBy() returns result sorted in ascending order java


I am sending result in descending order but I get output with ascending order

List<myEntity> myData = new ArrayList<>();
Map<Integer,List<myEntity>> myid = new LinkedHashMap<>();

try {
    myData = myService.getData(id); 
    myid = myData.stream().collect(Collectors.groupingBy(myEntity::getDataId)); 

Here mydata is sorted by desc order but after creating collections by group data id my list get sorted with ascending order. I want my collection list to be descending order not ascending order.


Solution

  • As @Holger described in Java 8 is not maintaining the order while grouping , Collectors.groupingBy() returns a HashMap, which does not guarantee order.

    Here is what you can do:

    myid = myData.stream()
    .collect(Collectors.groupingBy(MyEntity::getDataId,LinkedHashMap::new, toList()));
    

    Would return a LinkedHashMap<Integer, List<MyEntity>>. The order will also be maintained as the list used by collector is ArrayList.