Java 流 - 地图<key, List<VO>> 到地图<key, List<String from VO>

Java streams - Map<key, List<VO>> to Map<key, List<String from VO>

我有 Map<KeyString, List<MyVO>>.

MyVO.java 包含:

String name;
int id;

我想把它映射到Map<KeyString, List<names from MyVO>

如何使用 java 8 个流实现此目的?

你可以这样使用:

Map<String, List<String>> response =
        map.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey, 
                        e -> e.getValue().stream()
                                .map(MyVO::getName)
                                .collect(Collectors.toList())));

我正在使用唱片进行演示。 class 也适用于此。

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 中的原始密钥。
  • 并流式传输 VO 列表以提取字符串并创建新列表。
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]

解决方案:

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]}