在 HashMap 中添加到列表的快捷方式 [英] Shortcut for adding to List in a HashMap

查看:34
本文介绍了在 HashMap 中添加到列表的快捷方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常需要获取一个对象列表,并根据对象中包含的值将它们分组到一个 Map 中.例如.按国家/地区获取用户和组列表.

I often have a need to take a list of objects and group them into a Map based on a value contained in the object. Eg. take a list of Users and group by Country.

我的代码通常如下所示:

My code for this usually looks like:

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);
    }
}

然而,我不禁认为这很尴尬,有些大师有更好的方法.到目前为止我能看到的最接近的是 来自 Google 集合的 MultiMap.

However I can't help thinking that this is awkward and some guru has a better approach. The closest I can see so far is the MultiMap from Google Collections.

是否有任何标准方法?

谢谢!

推荐答案

在 Java 8 中,您可以使用 Map#computeIfAbsent().

In Java 8 you can make use of 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() 直接从ListMap:

Or, make use of Stream API's Collectors#groupingBy() to go from List to Map directly:

Map<String, List<User>> usersByCountry = listOfUsers.stream().collect(Collectors.groupingBy(User::getCountry));

在 Java 7 或更低版本中,您可以获得的最佳内容如下:

In Java 7 or below, best what you can get is below:

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 没有某种 LazyMapLazyList,但您可以使用 Multimap下面多基因润滑剂的答案.

Commons Collections has a LazyMap, but it's not parameterized. Guava doesn't have sort of a LazyMap or LazyList, but you can use Multimap for this as shown in answer of polygenelubricants below.

这篇关于在 HashMap 中添加到列表的快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆