Close

Java 8 Streams - Collectors.collectingAndThen Examples

Java 8 Streams Java Java API 


Class:

java.util.stream.Collectors

java.lang.Objectjava.lang.Objectjava.util.stream.Collectorsjava.util.stream.CollectorsLogicBig

Method:

public static <T,A,R,RR> Collector<T,A,RR> collectingAndThen(Collector<T,A,R> downstream,

Function<R,RR> finisher)

Adapts a Collector to perform an additional finishing transformation.

Type Parameters:
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:
downstream - a collector
finisher - a function to be applied to the final result of the downstream collector
Returns:
a collector which performs the action of the downstream collector, followed by an additional finishing step


Examples


The method Collectors#collectingAndThen collects each element per provided downStream collector and converts the type R (which returned from the downstream collector) to a final resultant type RR.

package com.logicbig.example.collectors;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CollectingAndThenExample {
public static void main (String[] args) {
Stream<String> s = Stream.of("apple", "banana", "orange");
List<String> synchronizedList = s.collect(Collectors.collectingAndThen(
Collectors.toList(), Collections::synchronizedList));
System.out.println(synchronizedList);
}
}

Output

[apple, banana, orange]
Original Post




See Also