简体   繁体   中英

Merging values from multiple HashMaps into a single List

I have 4 separate hashmaps all of the same type. 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. 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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