Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 947
sandy Avatar asked Dec 06 '22 11:12

sandy


2 Answers

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.

like image 197
MohammadReza Alagheband Avatar answered Mar 23 '23 00:03

MohammadReza Alagheband


Collectors.groupingBy returns a HashMap without any order as such (as to why you see "some order" is explained here). The correct way to do this is to specify the Map that preserve the order inside the Collectors.groupingBy:

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

))
like image 20
Eugene Avatar answered Mar 22 '23 22:03

Eugene