Java流:将<Enum,List <A >>映射到List <B>

yas*_*eco 2 java java-stream

我想使用Java流执行以下操作:

我有一个Map<Enum, List<A>>,我想将它转化到List<B>哪里B都有属性Enum, A.

因此,对于该键列表中的每个键和每个项目,我需要创建一个项目B并将所有项目收集到一个项目中List<B>.

如何使用Java流完成?

谢谢!

dan*_*niu 6

你可以flatMap把地图的条目变成Bs.

List<B> bList = map.entrySet().stream()
    // a B(key, value) for each of the items in the list in the entry
   .flatMap(e -> e.getValue().stream().map(a -> new B(e.getKey(), a)))
   .collect(toList());
Run Code Online (Sandbox Code Playgroud)