I have a Map<String, String>
that I want to transform to a Map<Type1,Type2>
using Java streams.
This is what I tried but I think I am getting the syntax wrong:
myMap.entrySet()
.stream()
.collect(Collectors.toMap(e -> Type1::new Type1(e.getKey()), e -> Type2::new Type2(e.getValue))));
Also tried
myMap.entrySet()
.stream()
.collect(Collectors.toMap(new Type1(Map.Entry::getKey), new Type2(Map.Entry::getValue));
But I just keep running compile errors. How do I do this transform?
It looks like what you really want is
myMap.entrySet()
.stream()
.collect(Collectors.toMap(
e -> new Type1(e.getKey()), e -> new Type2(e.getValue())));
though I admit it's honestly difficult to tell.
myMap.entrySet().stream()
.map(entry -> new AbstractMap.SimpleEntry(new Type1(entry.getKey()), new Type2(entry.getValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))
https://docs.oracle.com/javase/7/docs/api/java/util/AbstractMap.SimpleEntry.html
Or more elegantly:
myMap.entrySet().stream()
.map(this::getEntry)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
private Map.Entry<Type1, Type2> getEntry(Map.Entry<String, String> entry) {
return new AbstractMap.SimpleEntry(new Type1(entry.getKey()), new Type2(entry.getValue());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.