Shortcut for adding to List in a HashMap

Posted by Damo on Stack Overflow See other posts from Stack Overflow or by Damo
Published on 2010-06-10T23:58:05Z Indexed on 2010/06/11 0:02 UTC
Read the original article Hit count: 283

Filed under:
|
|

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

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.

Are there any standard approaches?

Thanks!

© Stack Overflow or respective owner

Related posts about java

Related posts about collections