This post will discuss the collectingAndThen() method provided by the Collectors class in Java, which adapts a collector to perform an additional finishing transformation.

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

1. Creating an immutable empty collection

⮚ Create an immutable empty List

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

⮚ Create an immutable empty Set

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

⮚ 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 collection

⮚ Create an immutable list

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

⮚ Create an immutable Set

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

⮚ 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 the collectingAndThen() method, as shown below:

Download  Run Code

Output:

[India, UK, USA]

4. Slice a list

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

Download  Run Code

Output:

[2, 3, 4, 5]

That’s all about the Collectors class collectingAndThen() method in Java.