我在弄清楚如何清理一些代码来执行此操作时遇到了麻烦:
我有一个Context
对象列表。每个Context
都有一个String userId
和一个Map<String, SomeObject> someObjects
。
我想将其展平到Map<String, SomeObjects>
kep所在的位置userId
。更具体地说:
class Context {
String userId;
Map<String, List<SomeObject>> // the String here is something other than userId
// other stuff, getters/setters
}
给定List<Context>
,我想获取Map<String, List<SomeObject>
但String实际上是userId的位置。
有一种干净的方法可以做到这一点吗?
假设aContext
具有aString userid
和a List<SomeObject> someObjects
:
Map<String, Set<SomeObject>> map = contexts.stream()
.collect(Collectors.toMap(Context::getUserid,
c -> c.getSomeObjects().values().stream()
.flatMap(Collection::stream)
.collect(Collectors.toSet())
));
这里的关键点是使用来将atoMap()
收集起来userid
并将flatmap()
其Stream<List<SomeObject>>
变成a,Stream<SomeObject>
因此您可以将它们收集到一个集合中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句