我有一个Map<KeyString, List<MyVO>>。
MyVO.java包含:
String name;
int id;我想把它映射到Map<KeyString, List<names from MyVO>中。
如何使用java 8流来实现这一点?
发布于 2021-09-08 14:00:53
你可以使用这样的东西:
Map<String, List<String>> response =
map.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().stream()
.map(MyVO::getName)
.collect(Collectors.toList())));发布于 2021-09-08 14:13:47
我在用唱片演示。一堂课也会在这里工作。
record VO(String getStr)
}首先创建一些数据
Map<String, List<VO>> map =
Map.of("A", List.of(new VO("S1"), new VO("S2")), "B",
List.of(new VO("S3"), new VO("S4")));
map.entrySet().forEach(System.out::println);版画
A=[VO[str=S1], VO[str=S2]]
B=[VO[str=S3], VO[str=S4]]Collectors.toMap.
Entry.
Map<String,List<String>> result = map.entrySet().stream()
.collect(Collectors.toMap(
Entry::getKey,
e -> e.getValue().stream().map(VO::getStr).toList()));版画
A=[S1, S2]
B=[S3, S4]发布于 2021-09-08 14:22:40
解决办法:
public static void mapNames() {
final Map<String, List<MyVO>> voMap = new HashMap<>();
voMap.put("all", Arrays.asList(
new MyVO(1, "John"),
new MyVO(2, "Bill"),
new MyVO(3, "Johanna")
));
final Map<String, List<String>> nameMap = voMap.entrySet().stream()
.filter(Objects::nonNull)
.collect(
Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().stream()
.map(MyVO::getName)
.collect(Collectors.toList())
));
System.out.println(nameMap);
}输出:
{all=[John, Bill, Johanna]}https://stackoverflow.com/questions/69104366
复制相似问题