How to convert Map<String, String> to Map<Long, String> ? (option : using guava)

@Vivin's answer is correct, but I think it's useful to explain why Guava doesn't have any method to allow you to transform the keys of a Map (or to transform a Set at all).

All of Guava's methods for transforming and filtering produce lazy results... the function/predicate is only applied when needed as the object is used. They don't create copies. Because of that, though, a transformation can easily break the requirements of a Set.

Let's say, for example, you have a Map<String, String> that contains both "1" and "01" as keys. They are both distinct Strings, and so the Map can legally contain both as keys. If you transform them using Long.valueOf(String), though, they both map to the value 1. They are no longer distinct keys. This isn't going to break anything if you create a copy of the map and add the entries, because any duplicate keys will overwrite the previous entry for that key. A lazily transformed Map, though, would have no way of enforcing unique keys and would therefore break the contract of a Map.


You can now use Java 8 stream, map, collect to do this in a more readable, clean manner.

Map<String, String> oldMap

Map<Long, String> newMap = oldMap.entrySet().stream()
  .collect(Collectors.toMap(entry -> Long.parseLong(entry.getKey()), Map.Entry::getValue));

UPDATE for Java 8

You can use streams to do this:

Map<Long, String> newMap = oldMap.entrySet().stream()
  .collect(Collectors.toMap(e -> Long.parseLong(e.getKey()), Map.Entry::getValue));

This assumes that all keys are valid string-representations of Longs. Also, you can have collisions when transforming; for example, "0" and "00" both map to 0L.


I would think that you'd have to iterate over the map:

Map<Long, String> newMap = new HashMap<Long, String>();
for(Map.Entry<String, String> entry : map.entrySet()) {
   newMap.put(Long.parseLong(entry.getKey()), entry.getValue());
}

This code assumes that you've sanitized all the values in map (so no invalid long values).

I'm hoping there is a better solution.

EDIT

I came across the CollectionUtils#transformedCollection(Collection, Transformer) method in Commons Collection-Utils that looks like it might do what you want. Scratch that, it only works for classes that implement Collection.

Tags:

Java

Guava