SoniEx2
SoniEx2

Reputation: 2034

How to convert a java map's values?

I have a TreeMap<String, WrappedObject> and I wanna convert it to a new, independent TreeMap<String, UnwrappedObject>. What's the simplest way to achieve this?

Upvotes: 1

Views: 85

Answers (4)

Stuart Marks
Stuart Marks

Reputation: 132360

This is one of those cases where Map.forEach comes in handy:

    Map<String, WrappedObject> in = ... ;
    Map<String, UnwrappedObject> out = new TreeMap<>();
    in.forEach((k, v) -> out.put(k, v.unwrap()));

(Assuming that WrappedObject.unwrap() does the obvious thing.)

The big advantage in brevity here is that Map.forEach passes the key and value separately, whereas the loop or streams approach requires use of Map.Entry instances and calls to its getters for the keys and values.

Upvotes: 2

Kayaman
Kayaman

Reputation: 73528

Assuming unwrap() unwraps a WrappedObject, you can't get much simpler than this.

TreeMap<String, UnwrappedObject> out = new TreeMap<>();
for(Entry<String, WrappedObject> entry : in.entrySet())
    out.put(entry.getKey(), unwrap(entry.getValue()));

Upvotes: 2

Sam
Sam

Reputation: 9944

Two questions: can you use Guava, and does the returned map need to be written to, or just read from?

If you can use Guava, and only need read access to the transformed map, you could use Maps.transformValues(NavigableMap, Function).

The advantage here is that there's virtually no cost other than the transformation of the values, yet the navigability of the map is retained. Other methods that construct a new TreeMap suffer from the cost of re-inserting every key.

Upvotes: 0

M A
M A

Reputation: 72844

If using Java 8:

Map<String, UnwrappedObject> newMap = wrappedObjectMap.entrySet()
    .stream()
    .collect(Collectors.toMap(Map.Entry::getKey,
                              e -> e.getValue().getWrappedObject());
                                  // assuming this method exists to get the UnwrappedObject

This collects all entries of the old map using a collector that takes the same key in the entry (Map.Entry::getKey is equivalent to e -> e.getKey()), and sets the value to be the result of unwrapping the object.

To have the returned map of type TreeMap, use the Collectors.toMap that takes a supplier:

TreeMap<String, Object> newMap = wrappedObjectMap.entrySet()
            .stream()
            .collect(Collectors.toMap(Map.Entry::getKey,
                                    e -> e.getValue().getWrappedObject(),
                                   (v1, v2) -> v1,
                                   TreeMap::new));
 // third parameter can be any merge function in this case since conflicts should not occur

Upvotes: 1

Related Questions