Java 按键缩小地图
Java Map Reduce By Key
我有一个配对列表如下:
// pairs = [(k1, obj1), (k2, obj1)]
List<Pair<String, Object> pairs;
然后我想把那些对象展开成很多对象,然后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
...);
我的问题是,如何对展开的对象进行key reduce,得到pairs列表?
我的意思是预期结果是:
pairs = [(k1, obj11), (k1, obj12), (k2, obj21), (k2, obj22)]
看起来你需要 flatMap
而不是 map
,collect
而不是 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());
我有一个配对列表如下:
// pairs = [(k1, obj1), (k2, obj1)]
List<Pair<String, Object> pairs;
然后我想把那些对象展开成很多对象,然后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
...);
我的问题是,如何对展开的对象进行key reduce,得到pairs列表?
我的意思是预期结果是:
pairs = [(k1, obj11), (k1, obj12), (k2, obj21), (k2, obj22)]
看起来你需要 flatMap
而不是 map
,collect
而不是 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());