2

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?

progNewbie
  • 4,362
  • 9
  • 48
  • 107
  • 2
    Please provide more example code... Do you have just a `Map` or an object containing that structure? Can't you implement some POJO that `implements Comparable`? – deHaar Aug 08 '18 at 08:15
  • which version of java do you use. and are these keys convertable to Integer ? – pvpkiran Aug 08 '18 at 08:19
  • 1
    @deHaar OP has already given the map signatures. Its not POJO, just String and Integer classes. But yes as suggested use a simple comparator which convert String to Integer internally. – Himanshu Bhardwaj Aug 08 '18 at 08:20

1 Answers1

3

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());
}
azro
  • 53,056
  • 7
  • 34
  • 70
Shubhendu Pramanik
  • 2,711
  • 2
  • 13
  • 23