我一直面临着多个需求,我需要将列表转换为Map,在某些情况下,我需要将2个字段组合为该map的键,之前我使用了以下解决方案-
Map<String, Integer> employeePairs = employees.stream().collect(HashMap<String, Integer>::new,
(m, c) -> m.put(c.getFirstName() + " " + c.getLastName(), c.employeeId),
(m, u) -> {
});我发现了一种新的方法,但它使用了不同的apache包,代码看起来像这样-
Map<Pair<String, String>, Integer> employeePairs = employees.stream().collect(HashMap<Pair<String, String>, Integer>::new,
(m, c) -> m.put(Pair.of(c.getFirstName(), c.getLastName()), c.employeeId),
(m, u) -> {
});
employeePairs.get(Pair.of("a1", "b1"));// way of accessing包装-
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>哪种方法更好?还是有更好的方法。
发布于 2020-10-06 01:21:35
如果您不想使用额外的库来仅使用Pair类,则可以使用AbstractMap.SimpleEntry将两个字段配对并收集为地图,最好使用Collectors.toMap
Map<AbstractMap.SimpleEntry<String, String>, Integer> employeePairs =
employees.stream()
.collect(Collectors.toMap(
c -> new AbstractMap.SimpleEntry<>(c.getFirstName(), c.getLastName()),
c -> c.employeeId
));您可以使用.getKey()和.getValue()访问AbstractMap.SimpleEntry的数据
https://stackoverflow.com/questions/64213300
复制相似问题