Learnitweb

Java 8 Collectors

In this tutorial we’ll discuss Collectors class and few of its important methods.

The Stream.collect() method

collect() method is provided by the Stream interface.

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

This method performs a mutable reduction operation on the elements of this stream using a Collector. A mutable reduction operation accumulates input elements into a mutable result container, such as a Collection or StringBuilder, as it processes the elements in the stream.

This is a terminal operation.

Collectors

Collectors class is present in java.util.stream package. This class contains implementation of Collector that implement various useful reduction operations, such as accumulating elements into collections. Methods of this class are static.

We’ll now discuss few important methods of Collectors class.

1. Collectors.toList()

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

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

Example: providedList.stream().collect(Collectors.toList());

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

public class CollectorsExample {
    public static void main(String[] args) {
    	//Create a list for demo purpose
    	List<String> providedList = Arrays.asList("one","two","three","four","five");
    	
    	//Collect element of stream to list
    	List<String> result =  providedList.stream().collect(Collectors.toList());
    	
    	System.out.println(result);
    }
}

Output

[one, two, three, four, five]

2. Collectors.toSet()

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

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

Example: providedList.stream().collect(Collectors.toSet());

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class CollectorsExample {
    public static void main(String[] args) {
    	//Create a list for demo purpose
    	List<String> providedList = Arrays.asList("one","two","three","four","five", "one", "two");
    	
    	//Collect element of stream to set
    	Set<String> result =  providedList.stream().collect(Collectors.toSet());
    	
    	System.out.println(result);
    }
}

Output

[four, one, two, three, five]

In this example, note that the duplicate element “one” and “two” are removed.

3. Collectors.toMap()

This method has three overloaded variations. Here, we’ll discuss one of these three methods.

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

This method 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.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class CollectorsExample {
    public static void main(String[] args) {
    	//Create a list for demo purpose
    	List<String> providedList = Arrays.asList("one","two","three","four","five");
    	
    	//Collect element of stream to map
    	Map<String, Integer> result = providedList.stream().collect(
    			Collectors.toMap(
    					x -> x.toUpperCase(), // keyMapper function 
    					x -> x.length()) 	  // valueMapper function
    			);
    	
    	System.out.println(result);
    }
}

Output

{FIVE=4, FOUR=4, ONE=3, TWO=3, THREE=5}

Note: IllegalStateException is thrown in case of duplicate keys.

4. Collectors.toCollection()

It is difficult to assume the implementation of the result of toList() and toSet() collectors. You can use toCollection() method to get result in specific collection.

For example, following example accumulates elements in a LinkedList.

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

public class CollectorsExample {
    public static void main(String[] args) {
    	//Create a list for demo purpose
    	List<Integer> providedList = Arrays.asList(1,2,3,4,5);
    	
    	//Accumulate elements in LinkedList
    	LinkedList<Integer> result = providedList.stream().collect(Collectors.toCollection(LinkedList::new));
    	
    	System.out.println(result);
    	System.out.println(result.getClass());
    }
}

Output

[1, 2, 3, 4, 5]
class java.util.LinkedList

5. Collectors.counting()

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

This method counts the number of input elements.

Example: providedList.stream().collect(Collectors.counting());

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

public class CollectorsExample {
    public static void main(String[] args) {
    	//Create a list for demo purpose
    	List<String> providedList = Arrays.asList("one","two","three","four","five");
    	
    	//count number of elements
    	long count = providedList.stream().collect(Collectors.counting());
    	
    	System.out.println(count);
    }
}

Output

5

6. Collectors.joining()

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

This method returns a Collector that concatenates the input elements into a String.

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

public class CollectorsExample {
    public static void main(String[] args) {
    	//Create a list for demo purpose
    	List<String> providedList = Arrays.asList("one","two","three","four","five");
    	
    	//join elements
    	String result = providedList.stream().collect(Collectors.joining());
    	
    	System.out.println(result);
    }
}

Output

onetwothreefourfive

7. Collectors.maxBy()

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

This method returns a Collector that produces the maximal element according to a given Comparator.

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

public class CollectorsExample {
    public static void main(String[] args) {
    	//Create a list for demo purpose
    	List<Integer> providedList = Arrays.asList(1,2,3,4,5);
    	
    	//get maximal element as Optional<Integer>
    	Optional<Integer> result = providedList.stream().collect(Collectors.maxBy(Comparator.naturalOrder()));
    	
    	System.out.println(result);
    }
}

Output

Optional[5]

8. Collectors.minBy()

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

This method returns a Collector that produces the minimal element according to a given Comparator, described as an Optional.

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

public class CollectorsExample {
    public static void main(String[] args) {
    	//Create a list for demo purpose
    	List<Integer> providedList = Arrays.asList(1,2,3,4,5);
    	
    	//get maximal element as Optional<Integer>
    	Optional<Integer> result = providedList.stream().collect(Collectors.minBy(Comparator.naturalOrder()));
    	
    	System.out.println(result);
    }
}

Output

Optional[1]