我想将类型转换List<A>为List<B>.我可以用java 8流方法吗?
Map< String, List<B>> bMap = aMap.entrySet().stream().map( entry -> {
List<B> BList = new ArrayList<B>();
List<A> sList = entry.getValue();
// convert A to B
return ???; Map( entry.getKey(), BList) need to return
}).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
Run Code Online (Sandbox Code Playgroud)
我尝试使用此代码,但无法在map()中进行转换.
Pel*_*cho 10
如果我理解正确你有一个Map<String, List<A>>,你想将它转换为Map<String, List<B>>.你可以这样做:
Map<String, List<B>> result = aMap.entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey(), // Preserve key
entry -> entry.getValue().stream() // Take all values
.map(aItem -> mapToBItem(aItem)) // map to B type
.collect(Collectors.toList()) // collect as list
);
Run Code Online (Sandbox Code Playgroud)
您可以AbstractMap.simpleEntry在map函数中实例化并执行转换。
例如,以下代码转换List<Integer>为List<String>:
Map<String, List<Integer>> map = new HashMap<>();
Map<String, List<String>> transformedMap = map.entrySet()
.stream()
.map(e -> new AbstractMap.SimpleEntry<String, List<String>>(e.getKey(), e.getValue().stream().map(en -> String.valueOf(en)).collect(Collectors.toList())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3590 次 |
| 最近记录: |