英文:
What is the best way to combine 2 or more fields as a Key in a Map, using Java 8?
问题
我一直面临多个需求,需要将列表转换为映射,并且在某些情况下,我需要将两个字段组合作为映射的键。以前我使用了以下解决方案 -
Map<String, Integer> employeePairs = employees.stream().collect(HashMap<String, Integer>::new,
(m, c) -> m.put(c.getFirstName() + " " + c.getLastName(), c.employeeId),
(m, u) -> {
});
我找到了一个新的方法,但它使用了不同的包apache Pair,代码如下 -
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"));// 访问的方式
依赖包 -
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
哪种方法更好?还有更好的方法吗?
英文:
I have been facing multiple requirements where I need to convert a List to Map, and in some cases I need to combine 2 fields as keys for that map, Previously I used the below solution -
Map<String, Integer> employeePairs = employees.stream().collect(HashMap<String, Integer>::new,
(m, c) -> m.put(c.getFirstName() + " " + c.getLastName(), c.employeeId),
(m, u) -> {
});
I found a new way but that use a different package apache Pair the code looks like this-
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
Package -
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
Which is a better way? Or is there a more better way.
答案1
得分: 1
如果您不想为仅使用Pair
类而使用额外的库,您可以使用AbstractMap.SimpleEntry<K,V>来配对两个字段并收集为映射,最好使用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
的数据。
英文:
If you don't want to use an extra library for using only Pair
class,
you can use AbstractMap.SimpleEntry<K,V> for pairing two fields and to collect as map, it's better to use 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
));
You can access data of AbstractMap.SimpleEntry
using .getKey()
and .getValue()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论