Java - Stream Collect Operation

Introduction

The following method collect() method takes an instance of the Collector interface as an argument and collects the data.

<R,A> R collect(Collector<? super T,A,R> collector)

The Collector interface is the java.util.stream package and it is declared as follows.

Only abstract methods are shown.

public interface Collector<T,A,R> {
        Supplier<A> supplier();
        BiConsumer<A,T> accumulator();
        BinaryOperator<A> combiner();
        Function<A,R> finisher();
        Set<Collector.Characteristics> characteristics();
}

The Collector interface takes three type parameters called T, A, and R, where

  • T is the type of input elements,
  • A is the type of the accumulator, and
  • R is the type of the result.

The finisher is used to transform the intermediate type A to result type R.

Collectors class provides out-of-box implementations for commonly used collectors.

Three of the most commonly used methods of the Collectors class are toList(), toSet(), and toCollection().

MethodDescription
toList() returns a Collector that collects the data in a List
toSet() returns a Collector that collects data in a Set
toCollecton() takes a Supplier that returns a Collection to be used to collect data.

The following code collects all names of people in a List<String>:

List<String> names = Person.persons()
                           .stream()
                           .map(Person::getName)
                           .collect(Collectors.toList());
System.out.println(names);

The following code collects all names in a Set<String>. Note that a Set keeps only unique elements.

Set<String> uniqueNames = Person.persons()
                                 .stream()
                                 .map(Person::getName)
                                 .collect(Collectors.toSet());
System.out.println(uniqueNames);

You can collect names in a sorted set using the toCollection() method as follows:

SortedSet<String> uniqueSortedNames= Person.persons()
                                           .stream()
                                           .map(Person::getName)
                                           .collect(Collectors.toCollection(TreeSet::new));
System.out.println(uniqueSortedNames);

You can sort the list of names using the sorted operation.

sorted() method of the Stream interface produces another stream containing the same elements on a sorted order.

The following code shows how to collect sorted names in a list:

List<String> sortedName = Person.persons()
                                .stream()
                                .map(Person::getName)
                                .sorted()
                                .collect(Collectors.toList());
System.out.println(sortedName);

Counting the number of people in the streams:

long count = Person.persons()
                   .stream()
                   .collect(Collectors.counting());
System.out.println("Person count: " + count);

Demo

import java.time.LocalDate;
import java.time.Month;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
  public static void main(String[] args) {
      List<String> sortedNames = Person.persons()
                                       .stream()
                                       .map(Person::getName)
                                       .sorted()
                                       .collect(Collectors.toList());
      System.out.println(sortedNames);
  }/*from  ww  w. j a va 2 s . c o m*/
}

class Person {
  // An enum to represent the gender of a person
  public static enum Gender {
    MALE, FEMALE
  }

  private long id;
  private String name;
  private Gender gender;
  private LocalDate dob;
  private double income;

  public Person(long id, String name, Gender gender, LocalDate dob, double income) {
    this.id = id;
    this.name = name;
    this.gender = gender;
    this.dob = dob;
    this.income = income;
  }

  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

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

  public Gender getGender() {
    return gender;
  }

  public boolean isMale() {
    return this.gender == Gender.MALE;
  }

  public boolean isFemale() {
    return this.gender == Gender.FEMALE;
  }

  public void setGender(Gender gender) {
    this.gender = gender;
  }

  public LocalDate getDob() {
    return dob;
  }

  public void setDob(LocalDate dob) {
    this.dob = dob;
  }

  public double getIncome() {
    return income;
  }

  public void setIncome(double income) {
    this.income = income;
  }

  public static List<Person> persons() {
    Person ken = new Person(1, "Java", Gender.MALE, LocalDate.of(1970, Month.MAY, 4), 6020.0);
    Person jeff = new Person(2, "Jack", Gender.MALE, LocalDate.of(1970, Month.JULY, 15), 7320.0);
    Person donna = new Person(3, "Javascript", Gender.FEMALE, LocalDate.of(1972, Month.JULY, 29), 8720.0);
    Person chris = new Person(4, "XML", Gender.MALE, LocalDate.of(1993, Month.DECEMBER, 16), 5800.0);
    Person laynie = new Person(5, "Json", Gender.FEMALE, LocalDate.of(2002, Month.DECEMBER, 13), 0.0);
    Person lee = new Person(6, "Database", Gender.MALE, LocalDate.of(2011, Month.MAY, 9), 2400.0);

    // Create a list of persons
    List<Person> persons = Arrays.asList(ken, jeff, donna, chris, laynie, lee);

    return persons;
  }

  @Override
  public String toString() {
    String str = String.format("(%s, %s, %s, %s, %.2f)", id, name, gender, dob, income);
    return str;
  }
}

Result

Related Topics