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.
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.
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()
))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With