Search code examples
javaguava

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


I have a Map<String, String> the String key is nothing but numeric value like "123" etc. I'm getting numeric value because this values are coming from the UI in my JSF component. I don't want to change the contract of UI component.

Now I would like to create a Map<Long, String> based on the above Map, I saw some transform methods in the Maps class but all are focusing on the converting value and not key.

Is there any better way to convert Map<String, String> to Map<Long, String> ?


Solution

  • 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.