After merging two maps I noticed that the last one is placed at the top when displaying the merged map :
Map<Integer, String> dataToSage = new HashMap<Integer, String>();
for(InterventionDTO i : list) {
Map<Integer, String> data = interfaceSageService.getDataToSendToSAGEFromIntervPlanMP(i.getIdintervention());
data.forEach((key, value) -> dataToSage.merge(key, value, (oldValue, newValue) -> {
return newValue;
}));
}
It gives an output of :
Although in the database the data is well ordered :
So how to place the last merged map at the bottom in the merge process ?
CodePudding user response:
You should not assume any ordering when using HashMap
.
If you need an ordering then you have two options:
- If you want elements to be sorted based on ordering of keys, then you can use
TreeMap
. If you need other than natural ordering you can passComparator
to the constructor. - If you want elements to be ordered based on their insertion order then you can use
LinkedHashMap
.