The collectingAndThen(Collector downstream, Function finisher) method of class collectors in Java, which adopts Collector so that we can perform an additional finishing transformation.
Syntax :
public static <T, A, R, RR> Collector <T, A, RR> collectingAndThen(Collector <T, A, R> downstream, Function <R, RR> finisher) Where,
Parameters:This method accepts two parameters which are listed below
Returns: Returns a collector which performs the action of the downstream collector, followed by an additional finishing step, with the help of finisher function.
Below are examples to illustrate collectingAndThen() the method.
Example 1: To create an immutable list
// Write Java code here // Collectors collectingAndThen() method import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create an Immutable List List<String> lt = Stream .of( "GEEKS" , "For" , "GEEKS" ) .collect(Collectors .collectingAndThen( Collectors.toList(), Collections::<String> unmodifiableList)); System.out.println(lt); } } |
[GEEKS, For, GEEKS]
Example 2: To create an immuitable set.
// Write Java code here import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create an Immutable Set Set<String> st = Stream .of( "GEEKS" , "FOR" , "GEEKS" ) .collect( Collectors .collectingAndThen(Collectors.toSet(), Collections::<String> unmodifiableSet)); System.out.println(st); } } |
[GEEKS, FOR]
Example 2: To create an immutable map
import java.util.*; public class GFG { public static void main(String[] args) { // Create an Immutable Map Map<String, String> mp = Stream .of( new String[][] { { "1" , "Geeks" }, { "2" , "For" }, { "3" , "Geeks" } }) .collect( Collectors .collectingAndThen( Collectors.toMap(p -> p[ 0 ], p -> p[ 1 ]), Collections::<String, String> unmodifiableMap)); System.out.println(mp); } } |
{1=Geeks, 2=For, 3=Geeks}
Note:This method is most commonly used for creating immutable collections.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.