猿问

如何从HashMap <String,List <E >>获取List <E>

我想List<E>从使用Map<String, List<E>>(E是一个随机类)中提取一个stream()。


我想要一个使用Java 8流的简单的单行方法。


到目前为止,我一直在尝试:


HashMap<String,List<E>> map = new HashMap<>();

List<E> list = map.values(); // does not compile

list = map.values().stream().collect(Collectors.toList()); // does not compile


慕的地8271018
浏览 312回答 3
3回答

慕尼黑5688855

map.values()返回一个Collection<List<E>>not List<E>,如果需要后者,则需要按以下步骤将嵌套拼合List<E>为单个List<E>:List<E> result = map.values()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .flatMap(List::stream)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());

当年话下

或使用&nbsp;forEach&nbsp;map.forEach((k,v)->list.addAll(v));或如Aomine所评论使用的map.values().forEach(list::addAll);

慕尼黑的夜晚无繁华

这是使用Java-9及更高版本的替代方法:List<E> result = map.values()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.flatMapping(List::stream, Collectors.toList()));
随时随地看视频慕课网APP

相关分类

Java
我要回答