Home > database >  How to place the merged map to the bottom?
How to place the merged map to the bottom?

Time:11-15

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 :

enter image description here

Although in the database the data is well ordered :

enter image description here

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:

  1. 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 pass Comparator to the constructor.
  2. If you want elements to be ordered based on their insertion order then you can use LinkedHashMap.
  • Related