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:
Would return a
LinkedHashMap<Integer, List<MyEntity>>
. The order will also be maintained as the list used by collector is ArrayList.Collectors.groupingBy
returns aHashMap
without any order as such (as to why you see "some order" is explained here). The correct way to do this is to specify theMap
that preserve the order inside theCollectors.groupingBy
:collect(Collectors.groupingBy())
returns a newMap
which overwrites the variable to your previousLinkedHashMap
. Your initial assignment is therefore futile. The exact type returned is undefined by the specs but in my test run it returned aHashMap
. (Never assume this will always be the case across different versions and brands of Java!)But the main issue is that you're storing
Integer
as keys. If the values of those keys is smaller than the modulus of the table inside theHashMap
, they will just appear ordered (because thehashCode
of anInteger
is just it;s value). When I tested with 1000Integer
values of 0..999, the hashtable (the array as part of the inner workings ofHashMap
) appeared to be of size 2048. (Again, undocumented so don't assume it!)In summary, the reason you see the results in ascending order is because of an implementation artifact, not because there's a specific reason.
You need reverse order of map. So In
java 8
, i solved with this.Entryset
gives usIntegers
of this map ofmyid
. So sort and get from first map which ismyid
and put infinalMap