在Java
8中,您可以使用
Map#computeIfAbsent()。
Map<String, List<User>> usersByCountry = new HashMap<>();for (User user : listOfUsers) { usersByCountry.computeIfAbsent(user.getCountry(), k -> new ArrayList<>()).add(user);}或者,请使用流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,但没有参数化。番石榴没有
LazyMap或的种类
LazyList,但是您可以使用
Multimap它,如下面的的答案



