Collectors collectingAndThen() method in Java with Examples
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, T : The type of the input elements A :Intermediate accumulation type of the downstream collector R :Result type of the downstream collector RR :Result type of the resulting collector
Parameters:This method accepts two parameters which are listed below
- downstream: It is an instance of a collector, i.e we can use any collector can here.
- finisher: It is an instance of a function which is to be applied to the final result of the downstream collector.
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
Java
// 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); } } |
Output:
[GEEKS, For, GEEKS]
Example 2: To create an immutable set.
Java
// 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); } } |
Output:
[GEEKS, FOR]
Example 2: To create an immutable map
Java
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); } } |
Output:
{1=Geeks, 2=For, 3=Geeks}
Note:This method is most commonly used for creating immutable collections.
Please Login to comment...