Blake Rivell
Blake Rivell

Reputation: 13875

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

Upvotes: 1

Views: 49

Answers (2)

Marc G. Smith
Marc G. Smith

Reputation: 886

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

Upvotes: 4

Jacob G.
Jacob G.

Reputation: 29680

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

Upvotes: 3

Related Questions