我经常需要获取对象列表并根据对象中包含的值将它们分组到 Map 中。例如。按国家/地区列出用户和组。
我的代码通常如下所示:
Map<String, List<User>> usersByCountry = new HashMap<String, List<User>>();
for(User user : listOfUsers) {
if(usersByCountry.containsKey(user.getCountry())) {
//Add to existing list
usersByCountry.get(user.getCountry()).add(user);
} else {
//Create new list
List<User> users = new ArrayList<User>(1);
users.add(user);
usersByCountry.put(user.getCountry(), users);
}
}
但是我不禁认为这很尴尬,有些大师有更好的方法。到目前为止我能看到的最接近的是 MultiMap from Google Collections .
有没有标准的方法?
谢谢!
最佳答案
从 Java 8 开始,您可以使用 Map#computeIfAbsent()
.
Map<String, List<User>> usersByCountry = new HashMap<>();
for (User user : listOfUsers) {
usersByCountry.computeIfAbsent(user.getCountry(), k -> new ArrayList<>()).add(user);
}
或者,使用 Stream API 的 Collectors#groupingBy()
直接从 List
到 Map
:
Map<String, List<User>> usersByCountry = listOfUsers.stream().collect(Collectors.groupingBy(User::getCountry));
在 Java 7 或更低版本中,你能得到的最好的结果如下:
Map<String, List<User>> usersByCountry = new HashMap<>();
for (User user : listOfUsers) {
List<User> users = usersByCountry.get(user.getCountry());
if (users == null) {
users = new ArrayList<>();
usersByCountry.put(user.getCountry(), users);
}
users.add(user);
}
Commons Collections有一个 LazyMap
,但它没有参数化。 Guava没有 LazyMap
或 LazyList
,但你可以使用 Multimap
如answer of polygenelubricants below所示.
关于java - 在 HashMap 中添加到 List 的快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3019376/