Search code examples
javajava-8mapreducereduce

Java Map Reduce By Key


I have a list of pairs as follows:

// pairs = [(k1, obj1), (k2, obj1)]
List<Pair<String, Object> pairs;

Then I want to expand those objects to many objects and reduce them by key

pairs.stream().map(pair -> {
                // every object is expanded into many objects, obj11, obj12, ...
                List<Object> objects = expand(pair.getRight());
                // the return is [(k1, obj11), (k1, obj12), (k2, obj21), (k2, obj22)]
                return objects.stream().map(object -> new MutablePair<String, Object>(pair.getLeft(), object)).collect(Collectors.toList());
            }).reduce(...
                // how to reduce it by key and get a list of pairs 
            ...);

My question is, how to reduce the expanded objects by key and get a list of pairs?

I mean the expected result is:

pairs = [(k1, obj11), (k1, obj12), (k2, obj21), (k2, obj22)]

Solution

  • Looks like you need flatMap instead of map, and collect instead of reduce:

    List<Pair<String, Object>> expandedPairs =
        pairs.stream()
             .flatMap(pair -> expand(pair.getRight()).stream()
                                                     .map(object -> new MutablePair<String, Object>(pair.getLeft(), object)))
             .collect(Collectors.toList());