[英]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.