Reputation: 319
I have a Map and I want to convert it to Map. The keys from the first Map will be equal to the ones in the second. MyObject has a property that I want to use as the value for the second map. So what I have now is a for loop that does:
for (Map.Entry<String, MyObject> entry : originalMap.getTextMessages().entrySet()) {
newMap.put(entry.getKey(), entry.getValue().getStringValue());
}
Now I've got the feeling it could be easier... can anyone shed a light on this? We're using Java 7 by the way but if you have some clever Java 8 function for this, please share it too.
Upvotes: 1
Views: 627
Reputation: 161
you can do it with help of guava:
import org.guava.collect.Maps;
Map<String, String> newMap = Maps.transformEntries(oldMap, new Maps.EntryTransformer<String, Object, String>() {
@Override
public String transformEntry(@Nullable String key, @Nullable Object value) {
return value == null ? null : value.toString();
}
});
Upvotes: 0
Reputation: 250
In Java7 you can do it with help of Apache commons collections:
import org.apache.commons.collections4.MapUtils;
Map<String, String> newMap = MapUtils.transformedMap(originalMap, TransformerUtils.<String>nopTransformer(), new Transformer<Object, String>() {
@Override
public String transform(final Object objectValue) {
return objectValue.toString();
}
});
Upvotes: 0
Reputation: 48404
Here's another Java 8 example with streams and a BiConsumer
, all in a main
method:
public static void main(String[] args) throws Exception {
class MyObject {
String s;
MyObject(String s) {
this.s = s;
}
String getStringValue() {
return s;
}
}
Map<String, MyObject> original = new HashMap<String, MyObject>();
original.put("original", new MyObject("0"));
Map<String, String> converted = new HashMap<String, String>();
// iterates each entry and puts the conversion in the new map
original.forEach((s,m) -> {converted.put(s, m.getStringValue());});
System.out.println(converted);
}
Output
{original=0}
Upvotes: 0
Reputation: 393821
It's quite straight forward with Java 8 Streams :
Map<String,String> newMap =
originalMap.entrySet().stream().collect(Collectors.toMap(e->e.getKey(),e->e.getValue().getStringValue()));
In Java 7 I think you can't do it with less code than you already have.
Upvotes: 3