Java 加入名单<;字符串>;在地图里面
我正在尝试将Java 加入名单<;字符串>;在地图里面,java,java-8,java-stream,Java,Java 8,Java Stream,我正在尝试将映射转换为映射,其中每个键的值是通过将上一个映射中列表中的所有值合并而生成的联合字符串,例如: A -> ["foo", "bar", "baz"] B -> ["one", "two", "three"] 应转换为 A -> "foo|bar|baz" B -> "one|two|three" 使用Java 8 Streams API执行此任务的惯用方法是什么?您可以使用此任务 Map<String, String> result = map
映射
转换为映射
,其中每个键的值是通过将上一个映射中列表
中的所有值合并而生成的联合字符串,例如:
A -> ["foo", "bar", "baz"]
B -> ["one", "two", "three"]
应转换为
A -> "foo|bar|baz"
B -> "one|two|three"
使用Java 8 Streams API执行此任务的惯用方法是什么?您可以使用此任务
Map<String, String> result = map.entrySet()
.stream()
.collect(toMap(
Map.Entry::getKey,
e -> e.getValue().stream().collect(joining("|")))
);
Map result=Map.entrySet()
.stream()
.收集(
Map.Entry::getKey,
e->e.getValue().stream().collect(加入(“|”))
);
在此代码中,地图中的每个条目都会收集到一个新地图,其中:
- 钥匙保持不变
- 值是一个列表,通过将所有元素连接在一起,收集到
字符串中
- 谷歌番石榴有一个很好的帮助方法:
com.google.common.collect.Maps.transformValues(map, x -> x.stream().collect(joining("|")));
使用纯java,这将起作用:
map.entrySet().stream().collect(toMap(Entry::getKey, e -> e.getValue().stream().collect(joining("|"))));
只需使用,无需创建嵌套流:
Map<String, String> result = map.entrySet()
.stream()
.collect(toMap(
e -> e.getKey(),
e -> String.join("|", e.getValue())));
Map result=Map.entrySet()
.stream()
.收集(
e->e.getKey(),
e->String.join(“|”,e.getValue());
应该注意的是,映射。transformValues
不创建独立的逐字映射,而是创建原始映射的视图。