I have a map in this format: Map<String, Map<Integer, Long>>
and content like
{BCD={321=2}, ABC={123=1}, DEF={798=3}, CDE={564=1, 456=1}, GHI={908=2}}`
Is it possible sort the Long
value reverse, then String
and Integer
?
I have a map in this format: Map<String, Map<Integer, Long>>
and content like
{BCD={321=2}, ABC={123=1}, DEF={798=3}, CDE={564=1, 456=1}, GHI={908=2}}`
Is it possible sort the Long
value reverse, then String
and Integer
?
No.
You cannot sort contents of a Map
.
Sorting is only possible on things, which retain a sorting, like List
, TreeMap
or TreeSet
.
If you want the Map
contents to be sorted, just implement a Comparator
(e.g. Comparator<Map.Entry<String, Map<Integer, Long>>>
) which is capable of returning an integer representing the order of two entries and feed all contents of your Map
into a List<Map.Entry<String, Map<Integer, Long>>>
, which can then be sorted.
private static final Comparator<Map.Entry<String, Map<Integer, Long>>> COMPI = new Comparator<>() {
@Override
public int compare(Map.Entry<String, Map<Integer, Long>> obj1,
Map.Entry<String, Map<Integer, Long>>(obj2)) {
... return 0, if obj1 equal to obj2
... return 1, if obj1 lower than obj2
... return -1, if obj1 greater than obj2
}
public static List<Map.Entry<String, Map<Integer, Long>>> sortMyMap(Map<String, Map<Integer, Long>> myMap) {
List<Map.Entry<String, Map<Integer, Long>>> l = new java.util.ArrayList<>(myMap.entrySet());
Collections.sort(l, COMPI);
return l;
}
}
The most difficult part would be to implement the comparator correctly...