dev ツ dev ツ - 2 months ago 9
Java Question

Sorting in map on the basis of order of numeric key

I have a

Map<String,Map<Integer,String>>


Sample data in this map

("aa" , ((3, "xx"),(5, "yy"),(1,"zz")))

("bb" , (5, "zz"))


Here Integer key of the inner map lies between 1 to 5. It is basically a priority number.

Now I need to fetch value for some key (say
aa
). It should return values from the inner map with the highest priority number (key).

In above example ,
yy
should be returned.

Note: order of insertion of data in map has nothing to do with order of inner map's key.

What should I do -


  • Use sorted inner map on the basis of key while populating map data?

  • Iterate over the map with the highest priority value (5 in this case) to lowest (1 in this case)?

  • Sort inner map in ascending order of key and get the last value?


Answer

Options 2 & 3 are less efficient, because you will have to sort/iterate every time you poll for a value.

You can implement option #1 with a TreeMap and all the sorting will be handled for you as elements are added. Then use TreeMap#lastEntry() to get the entry with the highest key value.

Using some Java 8 features:

Map<String,TreeMap<Integer,String>> outerMap = new HashMap<>();

public void insert(String outerKey, Integer innerKey, String innerValue) {
    outerMap.computeIfAbsent(outerKey, k -> new TreeMap<>())
        .put(innerKey, innerValue);
}

public String pollHighest(String outerKey) {
    return Optional.ofNullable(outerMap.get(outerKey))
        .map(TreeMap::lastEntry)
        .map(Map.Entry::getValue)
        .orElse(null);
}