Search code examples
javamapstreemap

Map<String, String> to TreeMap<Integer, String>


I have a Map<String, String> object. I want to have it sorted by the keys, but the keys should be seen as integer. I just created an TreeMap<Integer, String>(myMapObject).

But this obviously does not work. How can I create a new TreeMap and change the keys from String to Integer?


Solution

  • You can use Collectors.toMap in Java 8:

    Map<Integer, String> map1 = map.entrySet().stream().collect(Collectors.toMap(entry -> Integer.parseInt(entry.getKey()), Map.Entry::getValue, (a, b) -> b));
    

    Or below traditional approach:

    Map<Integer, String> map1 = new HashMap<>();
    
    for(final Map.Entry<String, String> entry : map.entrySet()){
         map1.put(Integer.parseInt(entry.getKey()), entry.getValue());
    }