【发布时间】:2022-10-18 19:18:32
【问题描述】:
我有两个列表如下
List<String> keys = List.of("A1", "B1", "A2", "B2");
List<List<String>> values = List.of(List.of("A1", "B1"), List.of("A2", "B2"), List.of("A1", "B2"), List.of("A2", "B1"));
我想从这两个列表中制作一张地图在申报时.
Map<String, List<List<String>>> result = Map.ofEntries(
Map.entry("A1", List.of(List.of("A1", "B1"), List.of("A1", "B2"))),
Map.entry("A2", List.of(List.of("A2", "B2"), List.of("A2", "B1"))),
Map.entry("B1", List.of(List.of("A1", "B1"), List.of("A2", "B1"))),
Map.entry("B2", List.of(List.of("A2", "B2"), List.of("A1", "B2")))
)
如您所见,每个map entry 的值都聚集了包含键值的values entry。
我尝试使用stream api、map method 和filter method 制作这个 Map 对象。
Map<Object, Object> result1 = keys.stream()
.map(key -> List.of(key, values.stream().filter(value -> value.contains(key)).toList()))
.collect(Collectors.toMap(data -> data.get(0), data -> data.get(1)));
这有效,但看起来很难看。
我认为应该有比这更有效的方法。
告诉我改善这一点的最佳方法。
【问题讨论】:
标签: java java-stream