1

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>();
13
  • 1
    And what do you expect to do on collisions? Commented Aug 21, 2019 at 17:42
  • @Mike'Pomax'Kamermans There won't ever be collisions since it is just all of the values which will always be their own entities in memory, even if the properties are exactly the same it doesn't matter, I don't care about the keys. Commented Aug 21, 2019 at 17:43
  • 1
    If you only want the MyEntity side of all the HashMaps, consider ArrayList.AddAll() docs.oracle.com/javase/8/docs/api/java/util/… Commented Aug 21, 2019 at 17:44
  • 1
    So... all you care about is new arraylist(h1).addall(h2).addAll(h3) etc.? If so: that's part of the standard ArrayList API. Give its method list a read-over, it's worth knowing what it supports out of the box. Commented Aug 21, 2019 at 17:45
  • 1
    naturally; I assume anyone who doesn't want to iterate over a list actually means "I don't want to write my own for loop". Commented Aug 21, 2019 at 17:47

2 Answers 2

4
List<MyEntity> finalList = new ArrayList<MyEntity>();
finalList.addAll(hashMapOne.values());
finalList.addAll(hashMapTwo.values());
finalList.addAll(hashMapThree.values());
finalList.addAll(hashMapFour.values());
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.