有没有更好的方法把"Map“转换成"Map"?
Map<String, Collection<String>> collectionsMap = ...
Map<String, List<String>> listsaps =
collectionsMap.entrySet().stream()
.collect(Collectors.<Map.Entry<String, Collection<String>>,
String, List<String>>toMap(
Map.Entry::getKey,
e -> e. getValue().stream().collect(Collectors.toList())
)
);感谢您帮助我们改进
发布于 2018-03-01 03:01:33
对于这样的情况,我会考虑使用Map.forEach来执行有副作用的操作。map上的流有些麻烦,因为需要编写额外的代码来流式传输map条目,然后从每个条目中提取键和值。相反,Map.forEach将每个键和值作为单独的参数传递给函数。这看起来是这样的:
Map<String, Collection<String>> collectionsMap = ...
Map<String, List<String>> listsaps = new HashMap<>(); // pre-size if desired
collectionsMap.forEach((k, v) -> listsaps.put(k, new ArrayList<>(v)));如果您的地图很大,您可能希望预先调整目标的大小,以避免在其填充过程中重新进行散列。要正确地做到这一点,您必须知道HashMap将存储桶的数量,而不是元素的数量作为其参数。这需要除以默认载荷系数0.75,以便在给定一定数量的元素的情况下适当地预置大小:
Map<String, List<String>> listsaps = new HashMap<>((int)(collectionsMap.size() / 0.75 + 1));发布于 2018-02-22 21:41:53
1)在Collectors.toMap()中,您不需要重复泛型类型,因为这些类型是推断出来的。
所以:
collect(Collectors.<Map.Entry<String, Collection<String>>,
String, List<String>>toMap(...)可以替换为:
collect(Collectors.toMap(...)2)将集合转换为列表的方式也可以简化。
这一点:
e -> e. getValue().stream().collect(Collectors.toList())可以写成:
e -> new ArrayList<>(e.getValue())你可以这样写:
Map<String, List<String>> listsaps =
collectionsMap.entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> new ArrayList<>(e.getValue())
)
);发布于 2018-02-22 21:37:33
我认为这更容易读懂:
Map<String, List<String>> listsaps = new HashMap<>();
collectionsMap.entrySet()
.stream()
.forEach(e -> listsaps.put(e.getKey(), new ArrayList<>(e.getValue())));如果您只想将条目转换为列表,但实际上并不关心更改集合的类型,那么您可以使用map.replaceAll
collectionsMap.replaceAll((k, v) -> new ArrayList<>(v));https://stackoverflow.com/questions/48928735
复制相似问题