简体   繁体   English

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

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

I have 4 separate hashmaps all of the same type. 我有4个相同类型的单独的哈希图。 I would like to merge the values of them all into a single list. 我想将它们的所有值合并到一个列表中。 I know how to set a List to hashMapOne.values(), but this doesn't help me here since I need to add all values from all 4 lists. 我知道如何将列表设置为hashMapOne.values(),但这对我没有帮助,因为我需要添加所有4个列表中的所有值。 Can I do this without looping and individually adding each one? 我能做到这一点而无需循环并分别添加每个吗?

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());

If I were you, I'd just use Stream#of for all Map#values , and then call Stream#flatMap and Stream#collect to transform it to a List : 如果您是我,我将对所有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