JavaCodingNerd

Java Coding Nerd. This Blog will feature content-rich articles, tutorials and own opinions on variuos programming related topcis.

Java 8, Java Tutorial

How to: Group a List with Java Stream API

Asynchronus REST-Calls LocalDateTimeConverter

Asynchronus REST-Calls LocalDateTimeConverter

Grouping with Java Stream API

This will be a quick Guide on how to group a List using the Java Stream API which was introduced to Java 8.

Lets assume we have a Person Entity that looks like this

public class Person {

  private String name;
  private int age;
  private String nationality;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public String getNationality() {
    return nationality;
  }

  public void setNationality(String nationality) {
    this.nationality = nationality;
  }

}

 

No we have a list of Persons

Person sara = new Person("Sara", 4, "Norwegian");
Person viktor = new Person("Viktor", 40, "Serbian");
Person eva = new Person("Eva", 42, "Norwegian");

We want to get a list of persons grouped by their nationality

Map<String, List<Person>>

To do this before Java 8 you would have done something like this

public static Map<string, list<person="">> groupByNationality7(List people) {
       Map<string, list<person="">> map = new HashMap<>();
       for (Person person : people) {
           if (!map.containsKey(person.getNationality())) {
               map.put(person.getNationality(), new ArrayList<>());
           }
           map.get(person.getNationality()).add(person);
       }
       return map;
   }</string,></string,>

With Java 8 we can just write

public static Map<string, list<person="">> groupByNationality(List people) {
      return people.stream() 
              .collect(groupingBy(Person::getNationality)); 
  }</string,>

See more examples here 

 

Spread the love

Leave a Reply

Theme by Anders Norén