Collectors collectingAndThen() method in Java

In this post, we will discuss about collectingAndThen() method provided by Collectors class in Java which adapts a Collector to perform an additional finishing transformation.


 

The collectingAndThen(downstream, finisher) method returns a collector which performs the action of the downstream collector, followed by an additional finishing step with the help of finisher Function. It is most commonly used for creating immutable Collections.

 

1. Creating an Immutable Empty Collection

 

1.1. Create an Immutable Empty List

We could adapt the Collectors.toList() collector to always produce an immutable empty List as shown below:

 

1.2. Create an Immutable Empty Set

We could adapt the Collectors.toSet() collector to always produce an immutable empty Set as shown below:

 

1.3. Create an Immutable Empty Map

We could adapt the Collectors.toMap() collector to always produce an immutable empty Map as shown below:

 

Download   Run Code

 

2. Creating an Immutable Collections

 

2.1. Create an Immutable List

We could adapt the toList() collector to always produce an unmodifiable list with:

 

2.2. Create an Immutable Set

We could adapt the toSet() collector to always produce an unmodifiable set with:

 

2.3. Create an Immutable Map

We could adapt the toMap() collector to always produce an unmodifiable map with:

 

Download   Run Code

 

3. Reversing a List

We can also write a collector that collects elements in the reversed order with the help of collectingAndThen() method as shown below:

 

Download   Run Code

Output:

[India, UK, USA]

 

4. Slice a List

We can also use collectingAndThen() method to get slice of a List as shown below:

 

Download   Run Code

Output:

[2, 3, 4, 5]

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of