Signup/Sign In
LAST UPDATED: JUNE 30, 2020

Java 8 Collectors class

In Java 8 version, a new class is added to perform reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc.

The Collectors class applies to the Java stream So we recommend you to have an understanding of Stream, Lambda Expression, Method Reference as well. If you are not familiar with these, you can read these topics at our portal by clicking the topics.

The Collectors is a final class that extends Object class and located into java.util.stream package.

Declaration

public final class Collectors extends Object

Collector Class Methods

The following are the methods of the Collectors class.

Modifier and Type

Method and Description

static <T> Collector<T,?,Double> averagingDouble(ToDoubleFunction<? super T> mapper)

It returns a Collector that produces the arithmetic mean of a double-valued function applied to the input elements.

static <T> Collector<T,?,Double> averagingInt(ToIntFunction<? super T> mapper)

It returns a Collector that produces the arithmetic mean of an integer-valued function applied to the input elements.

static <T> Collector<T,?,Double> averagingLong(ToLongFunction<? super T> mapper)

It returns a Collector that produces the arithmetic mean of a long-valued function applied to the input elements.

static <T,A,R,RR> Collector<T,A,RR> collectingAndThen(Collector<T,A,R> downstream, Function<R,RR> finisher)

It adapts a Collector to perform an additional finishing transformation.

static <T> Collector<T,?,Long> counting()

It returns a Collector accepting elements of type T that counts the number of input elements.

static <T,K> Collector<T,?,Map<K,List<T>>> groupingBy(Function<? super T,? extends K> classifier)

It returns a Collector implementing a "group by" operation on input elements of type T, grouping elements according to a classification function, and returning the results in a Map.

static <T,K,A,D> Collector<T,?,Map<K,D>>

groupingBy(Function<? super T,? extends K> classifier, Collector<? super T,A,D> downstream)

It returns a Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.

static <T,K,D,A,M extends Map<K,D>>
Collector<T,?,M>

groupingBy(Function<? super T,? extends K> classifier, Supplier<M> mapFactory, Collector<? super T,A,D> downstream)

It returns a Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.

static <T,K> Collector<T,?,ConcurrentMap<K,List<T>>> groupingByConcurrent(Function<? super T,? extends K> classifier)

It returns a concurrent Collector implementing a "group by" operation on input elements of type T, grouping elements according to a classification function.

static <T,K,A,D> Collector<T,?,ConcurrentMap<K,D>>

groupingByConcurrent(Function<? super T,? extends K> classifier, Collector<? super T,A,D> downstream)

It returns a concurrent Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.

static <T,K,A,D,M extends ConcurrentMap<K,D>>
Collector<T,?,M>

groupingByConcurrent(Function<? super T,? extends K> classifier, Supplier<M> mapFactory, Collector<? super T,A,D> downstream)

It returns a concurrent Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.

static Collector<CharSequence,?,String> joining()

It returns a Collector that concatenates the input elements into a String, in encounter order.

static Collector<CharSequence,?,String> joining(CharSequence delimiter)

It returns a Collector that concatenates the input elements, separated by the specified delimiter, in encounter order.

static Collector<CharSequence,?,String> joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

It returns a Collector that concatenates the input elements, separated by the specified delimiter, with the specified prefix and suffix, in encounter order.

static <T,U,A,R> Collector<T,?,R>

mapping(Function<? super T,? extends U> mapper, Collector<? super U,A,R> downstream)

It adapts a Collector accepting elements of type U to one accepting elements of type T by applying a mapping function to each input element before accumulation.

static <T> Collector<T,?,Optional<T>> maxBy(Comparator<? super T> comparator)

It returns a Collector that produces the maximal element according to a given Comparator, described as an Optional<T>.

static <T> Collector<T,?,Optional<T>> minBy(Comparator<? super T> comparator)

It returns a Collector that produces the minimal element according to a given Comparator, described as an Optional<T>.

static <T> Collector<T,?,Map<Boolean,List<T>>> partitioningBy(Predicate<? super T> predicate)

It returns a Collector which partitions the input elements according to a Predicate, and organizes them into a Map<Boolean, List<T>>.

static <T,D,A> Collector<T,?,Map<Boolean,D>>

partitioningBy(Predicate<? super T> predicate, Collector<? super T,A,D> downstream)

It returns a Collector which partitions the input elements according to a Predicate, reduces the values in each partition according to another Collector, and organizes them into a Map<Boolean, D> whose values are the result of the downstream reduction.

static <T> Collector<T,?,Optional<T>> reducing(BinaryOperator<T> op)

It returns a Collector which performs a reduction of its input elements under a specified BinaryOperator.

static <T> Collector<T,?,T> reducing(T identity, BinaryOperator<T> op)

It returns a Collector which performs a reduction of its input elements under a specified BinaryOperator using the provided identity.

static <T,U> Collector<T,?,U>

reducing(U identity, Function<? super T,? extends U> mapper, BinaryOperator<U> op)

It returns a Collector which performs a reduction of its input elements under a specified mapping function and BinaryOperator.

static <T> Collector<T,?,DoubleSummaryStatistics> summarizingDouble(ToDoubleFunction<? super T> mapper)

It returns a Collector which applies an double-producing mapping function to each input element, and returns summary statistics for the resulting values.

static <T> Collector<T,?,IntSummaryStatistics> summarizingInt(ToIntFunction<? super T> mapper)

It returns a Collector which applies an int-producing mapping function to each input element, and returns summary statistics for the resulting values.

static <T> Collector<T,?,LongSummaryStatistics> summarizingLong(ToLongFunction<? super T> mapper)

It returns a Collector which applies an long-producing mapping function to each input element, and returns summary statistics for the resulting values.

static <T> Collector<T,?,Double> summingDouble(ToDoubleFunction<? super T> mapper)

It returns a Collector that produces the sum of a double-valued function applied to the input elements.

static <T> Collector<T,?,Integer> summingInt(ToIntFunction<? super T> mapper)

It returns a Collector that produces the sum of a integer-valued function applied to the input elements.

static <T> Collector<T,?,Long> summingLong(ToLongFunction<? super T> mapper)

It returns a Collector that produces the sum of a long-valued function applied to the input elements.

static <T,C extends Collection<T>>
Collector<T,?,C> toCollection(Supplier<C> collectionFactory)

It returns a Collector that accumulates the input elements into a new Collection, in encounter order.

static <T,K,U> Collector<T,?,ConcurrentMap<K,U>>

toConcurrentMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)

It returns a concurrent Collector that accumulates elements into a ConcurrentMap whose keys and values are the result of applying the provided mapping functions to the input elements.

static <T,K,U> Collector<T,?,ConcurrentMap<K,U>>

toConcurrentMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction)

It returns a concurrent Collector that accumulates elements into a ConcurrentMap whose keys and values are the result of applying the provided mapping functions to the input elements.

static <T,K,U,M extends ConcurrentMap<K,U>>
Collector<T,?,M>

toConcurrentMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier)

It returns a concurrent Collector that accumulates elements into a ConcurrentMap whose keys and values are the result of applying the provided mapping functions to the input elements.

static <T> Collector<T,?,List<T>> toList()

It returns a Collector that accumulates the input elements into a new List.

static <T,K,U> Collector<T,?,Map<K,U>>

toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)

It returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

static <T,K,U> Collector<T,?,Map<K,U>>

toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction)

It returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

static <T,K,U,M extends Map<K,U>>
Collector<T,?,M>

toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier)

It returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

static <T> Collector<T,?,Set<T>> toSet()

It returns a Collector that accumulates the input elements into a new Set.

In all these examples, we are using a class Employee that contains id, name, and salary of an employee as instance variables and a constructor and getter, setter methods for all the instance variables. Let's see how we will use it with the Collectors class.

Example

In this example, we are collecting names of all the employees and storing them into a list by using toList() method of Collectors class.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

class Employee{
	String id;
	String name;
	double salary;


	public Employee(String id, String name, double salary) {
		this.id = id;
		this.name = name;
		this.salary = salary;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
}

public class STDemo {
	public static void main(String[] args) {
		List<Employee> emp = new ArrayList<>();
		emp.add(new Employee("100", "Sohan", 120000));
		emp.add(new Employee("101", "Mohan", 100050));
		emp.add(new Employee("102", "Rohan", 500050));
		emp.add(new Employee("103", "John",  5000.20));

		List<String> names = emp.stream().map(Employee::getName).collect(Collectors.toList());

		System.out.println(names);
	}
}


[Sohan, Mohan, Rohan, John]

Example: TreeSet

In this example, we are getting names of all the employees into a set TreeSet. The set is used to store unique elements and see the result does not contain the duplicate names of the employee.

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class STDemo {
	public static void main(String[] args) {
		List<Employee> emp = new ArrayList<>();
		emp.add(new Employee("100", "Sohan", 120000));
		emp.add(new Employee("101", "Mohan", 100050));
		emp.add(new Employee("102", "Rohan", 500050));
		emp.add(new Employee("103", "Sohan",  5000.20));

		Set<String> names = emp.stream().map(Employee::getName).collect(Collectors.toCollection(TreeSet::new));

		System.out.println(names);
	}
}


[Mohan, Rohan, Sohan]

Example: Collecting data as String

In this example, we are using joining() method to collect all the employee's names and separate them by commas. The method returns a string after collecting the record.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class STDemo {
	public static void main(String[] args) {
		List<Employee> emp = new ArrayList<>();
		emp.add(new Employee("100", "Sohan", 120000));
		emp.add(new Employee("101", "Mohan", 100050));
		emp.add(new Employee("102", "Rohan", 500050));
		emp.add(new Employee("103", "Sohan",  5000.20));

		String names = emp.stream().map(Employee::getName).collect(Collectors.joining(", "));

		System.out.println(names);
	}
}


Sohan, Mohan, Rohan, Sohan

Example:

In this example, we are getting a sum of the salary of all the employees by using the summingDouble() method of Collectors class.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class STDemo {
	public static void main(String[] args) {
		List<Employee> emp = new ArrayList<>();
		emp.add(new Employee("100", "Sohan", 120000));
		emp.add(new Employee("101", "Mohan", 100050));
		emp.add(new Employee("102", "Rohan", 500050));
		emp.add(new Employee("103", "Sohan",  5000.20));

		double totalSalary = emp.stream()
                .collect(Collectors.summingDouble((Employee::getSalary)));

		System.out.println(totalSalary);
	}
}


725100.2

Example:

We can get the highest salary from the list of salaries by using the maxBy() method. It returns the highest record available in the list based on the provided element order.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class STDemo {
	public static void main(String[] args) {
		List<Employee> emp = new ArrayList<>();
		emp.add(new Employee("100", "Sohan", 120000));
		emp.add(new Employee("101", "Mohan", 100050));
		emp.add(new Employee("102", "Rohan", 500050));
		emp.add(new Employee("103", "Sohan",  5000.20));

		Optional<Double> highSalary = emp.stream().map(Employee::getSalary).collect(Collectors.maxBy(Comparator.naturalOrder()));
        

		System.out.println("Highest Salary : "+highSalary.get());
	}
}


Highest Salary : 500050.0



About the author:
I am a Java developer by profession and Java content creator by passion. I have over 5 years of experience in Java development and content writing. I like writing about Java, related frameworks, Spring, Springboot, etc.