Mapping Adapter for Downstream Collectors

The mapping() method of the Collectors class encapsulates a mapper function and a downstream collector to create an adapter for a mapping operation. (See also the map() intermediate operation, p. 921.)

Click here to view code image

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

Returns a Collector that applies the mapper function to input elements of type T and provides the mapped results of type U to the downstream collector that accumulates them into results of type R.

In other words, the method adapts a downstream collector accepting elements of type U to one accepting elements of type T by applying a mapper function to each input element before accumulation, where type parameter A is the intermediate accumulation type of the downstream collector.

The mapping() method at (1) creates an adapter that accumulates a set of CD titles in each year for a stream of CDs. The mapper function maps a CD to its title so that the downstream collector can accumulate the titles in a set.

Click here to view code image

Map<Year, Set<String>> titlesByYearInSet = CD.cdList.stream()
    .collect(Collectors.groupingBy(
        CD::year,
        Collectors.mapping(                           // (1)
            CD::title,                                // Mapper
            Collectors.toSet())));                    // Downstream collector
System.out.println(titlesByYearInSet);
// {2017=[Java Jive, Java Jam],
//  2018=[Hot Generics, Lambda Dancing, Keep on Erasing]}

The mapping() method at (2) creates an adapter that joins CD titles in each year for a stream of CDs. The mapper function maps a CD to its title so that the downstream collector can join the titles.

Click here to view code image

Map<Year, String> joinTitlesByYear = CD.cdList.stream()
    .collect(Collectors.groupingBy(
        CD::year,
        Collectors.mapping(                           // (2)
            CD::title,
            Collectors.joining(“:”))));
System.out.println(joinTitlesByYear);
// {2017=Java Jive:Java Jam,
//  2018=Lambda Dancing:Keep on Erasing:Hot Generics}

The mapping() method at (3) creates an adapter that counts the number of CD tracks for each year for a stream of CDs. The mapper function maps a CD to its number of tracks so that the downstream collector can count the total number of tracks.

Click here to view code image

Map<Year, Long> TotalNumOfTracksByYear = CD.cdList.stream()
    .collect(Collectors.groupingBy(
       CD::year,
       Collectors.mapping(                            // (3)
           CD::noOfTracks,
           Collectors.counting())));
System.out.println(TotalNumOfTracksByYear);           // {2017=2, 2018=3}

Leave a Reply

Your email address will not be published. Required fields are marked *