Close

Java 8 Streams - Collectors.mapping Examples

Java 8 Streams Java Java API 


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

The static method, Collector#mapping() returns a Collector which maps each element of the stream to type U and collect the mapped type according to a provided downstream Collector.

<T,U,A,R> Collector<T,?,R> mapping(Function<? super T,? extends U> mapper,

Collector<? super U,A,R> downstream)

Parameters

mapper: This function transforms the input values of type T to type U.

downstream: This collector transforms the values of type U to final type R.


Examples


package com.logicbig.example.collectors;

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

public class MappingExample {
public static void main (String[] args) {
Stream<String> s = Stream.of("apple", "banana", "orange");
List<String> list = s.collect(Collectors.mapping(s1 -> s1.substring(0, 2),
Collectors.toList()));
System.out.println(list);
}
}

Output

[ap, ba, or]
Original Post




See Also