Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by field name in Java

I'm trying to group Java objects by their field, i.e Person.java

public class Person {
    String name;
    String surname;
    ....
}

So if I have n Person objects, what would be the easiest way to get all people name "David" into a map like Map<String, List<Person>> map;?

I found this on Google (but it doesn't compile), it seems to be the thing I'm looking for: http://www.anzaan.com/2010/06/grouping-objects-using-objects-property/

like image 587
London Avatar asked Mar 21 '11 23:03

London


People also ask

How to do group by in Java?

The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance. In order to use it, we always need to specify a property by which the grouping would be performed. This method provides similar functionality to SQL's GROUP BY clause.

How does Groupby work in Java 8?

In Java 8, you retrieve the stream from the list and use a Collector to group them in one line of code. It's as simple as passing the grouping condition to the collector and it is complete. By simply modifying the grouping condition, you can create multiple groups.


2 Answers

There's probably a library that can do this more simply, but it's not too hard to do it manually:

List<Person> allPeople; // your list of all people
Map<String, List<Person>> map = new HashMap<String, List<Person>>();
for (Person person : allPeople) {
   String key = person.getName();
   if (map.get(key) == null) {
      map.put(key, new ArrayList<Person>());
   }
   map.get(key).add(person);
}

List<Person> davids = map.get("David");
like image 163
Kaleb Brasee Avatar answered Oct 05 '22 23:10

Kaleb Brasee


Using java-8 with the Collectors class and streams, you can do this:

Map<String, List<Person>> mapByName = 
    allPeople.stream().collect(Collectors.groupingBy(Person::getName));

List<Person> allDavids = mapByName.getOrDefault("David", Collections.emptyList());

Here I used getOrDefault so that you get an empty immutable list instead of a null reference if there is no "David" in the original list, but you can use get if you prefer to have a null value.

Hope it helps! :)

like image 26
Alexis C. Avatar answered Oct 05 '22 22:10

Alexis C.