MapStream.map* methods

Peter Levart peter.levart at marand.si
Tue May 8 01:06:08 PDT 2012


Hi Mike and others,

I'm trying to understand the purpose of the 3 MapStream.map* methods that have 
the following signatures:

public interface MapStream<K, V> {

    <W> MapStream<K, W> map(BiMapper<K, V, W> mapper) default ...

    <W> MapStream<K, W> mapValues(Mapper<V, W> mapper) default {
        return map( (k, v) -> mapper.map(v));
    }

    <W> MapStream<K, Iterable<W>> mapValuesMulti(
        BiMapper<? super K, ? super V, Iterable<W>> mapper
    ) default ...

... the first is obvious. It replaces the values in a key/value pairs with 
values computed by BiMapper from key/value pairs. This is the most common 
method and for the less common case (to replace keys instead of values) one 
can use the following idiom:

    mapStream.swap().map().swap()...

... the second (mapValues) is just a shorthand for the first in the common case 
when keys are not needed in the computation of values.

Now I think that both could have a more forgiving generic signature:

    <W> MapStream<K, W> map(
        BiMapper<? super K, ? super V, ? extends W> mapper
    );

    <W> MapStream<K, W> mapValues(Mapper<? super V, ? extends W> mapper);

... the third (mapValuesMulti) is the one that I don't see the point in. It is 
just a more constrained version of plain map(). Even the default 
implementation bodies are the same. Are those API choices only to help 
inferencing engine or I'm missing something?

What I'm missing is the following method:

    <W> MapStream<K, W> flatMap(
        BiMapper<? super K, ? super V, ? extends Iterable<W>>
    );

By analogy to the similar method in Iterable it could also be used to flatten 
(Multi)MapStreams:

    MapStream<X, Iterable<Y>> multiMapStream = ...;

    MapStream<X, Y> flattened = multiMapStream.flatMap((x, ys) -> ys);


On the other front, it would be nice to have the following method in 
MapStream:

    MapStream<K, Iterable<V>> groupByKey();



Regards,

Peter



More information about the lambda-dev mailing list