Premraj Premraj - 1 year ago 85
Java Question

How to convert Map<String, String> to Map<Long, String> using guava

I have a

Map<String, 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
, I saw some
methods in the
class but all are focusing on the converting value and not key.

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

Answer Source

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(new Long(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.


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download