Szymon Roziewski
Szymon Roziewski

Reputation: 1129

How to implement my own finisher in a collector?

Welcome people!

I am wondering how to implement my own finisher which is not trival, like identity function. The header of my collector is

public class SequentialPPSCollector<T> implements
    Collector<Pair<T, Double>, List<Pair<T, Double>>, List<T>> {...}

Inside there is a finisher method which should transform List<Pair<T, Double>> into List<T>

@Override
public Function<List<Pair<T, Double>>, List<T>> finisher() {
    return ...
}

This does the job

return list -> list
       .stream()
       .map(Pair::getLeft)
       .collect(Collectors.toList());

Upvotes: 1

Views: 2671

Answers (1)

Alexis C.
Alexis C.

Reputation: 93842

Here's how you can transform a List<Pair<T, Double>> into List<T>:

List<T> listOfT = list.stream()
                      .map(Pair::getFirst)
                      .collect(Collectors.toList());

So your finisher function could looks like this:

@Override
public Function<List<Pair<T, Double>>, List<T>> finisher() {
    return list -> list.stream().map(Pair::getFirst).collect(toList());
}


Although this example is a bit simple because in this case you could probably declare your collector like this:

class SequentialPPSCollector<T> implements Collector<Pair<T, Double>, List<T>, List<T>> {...} 

and let the accumulator grab the type T of the pair object:

@Override
public BiConsumer<List<T>, Pair<T, Double>> accumulator() {
    return (list, p) -> list.add(p.getFirst());
}

so that your finisher is simply the identity function. The first part of the answer should give you a starting point though.

Upvotes: 4

Related Questions