[英]How to transform the key and value of a each entry set of a Map using Java 8?
我有一个Map<String, String>
,我想使用Java流转换为Map<Type1,Type2>
。
这是我尝试过的,但我认为我的语法错误:
myMap.entrySet()
.stream()
.collect(Collectors.toMap(e -> Type1::new Type1(e.getKey()), e -> Type2::new Type2(e.getValue))));
也试过了
myMap.entrySet()
.stream()
.collect(Collectors.toMap(new Type1(Map.Entry::getKey), new Type2(Map.Entry::getValue));
但我只是继续运行编译错误。 我该如何改造?
它看起来像你真正想要的是
myMap.entrySet()
.stream()
.collect(Collectors.toMap(
e -> new Type1(e.getKey()), e -> new Type2(e.getValue())));
虽然我承认说老实说很难。
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
或者更优雅:
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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.