繁体   English   中英

将来自多个HashMap的值合并到一个列表中

[英]Merging values from multiple HashMaps into a single List

我有4个相同类型的单独的哈希图。 我想将它们的所有值合并到一个列表中。 我知道如何将列表设置为hashMapOne.values(),但这对我没有帮助,因为我需要添加所有4个列表中的所有值。 我能做到这一点而无需循环并分别添加每个吗?

HashMap<String, MyEntity> hashMapOne = new HashMap<String, MyEntity>();
HashMap<String, MyEntity> hashMapTwo = new HashMap<String, MyEntity>();
HashMap<String, MyEntity> hashMapThree = new HashMap<String, MyEntity>();
HashMap<String, MyEntity> hashMapFour = new HashMap<String, MyEntity>();

List<MyEntity> finalList = new ArrayList<MyEntity>();
List<MyEntity> finalList = new ArrayList<MyEntity>();
finalList.addAll(hashMapOne.values());
finalList.addAll(hashMapTwo.values());
finalList.addAll(hashMapThree.values());
finalList.addAll(hashMapFour.values());

如果您是我,我将对所有Map#values使用Stream#of ,然后调用Stream#flatMapStream#collect将其转换为List

List<MyEntity> finalList = Stream.of(hashMapOne.values(), hashMapTwo.values(), 
                                     hashMapThree.values(), hashMapFour.values())
      .flatMap(Collection::stream)
      .collect(Collectors.toList());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM