jsan
jsan

Reputation: 1057

Copying object from nested hashmap

I have the 2 following hashmaps where Message is an object i created.

HashMap<String, Message> hmA = new HashMap<>(); //A
HashMap<String, HashMap<String, Message>> hmFinal = new HashMap<>();

If i populate hmA with the following

hmA.put("Albert", new Message("Albert", "[email protected]", "122-4645 ));
hmA.put("Anthony", new Message("Anthony", "[email protected]", "570-5214"));
hmA.put("Alphonso", new Message("Alphonso", "[email protected]", "888-5314"));

Then I add hmA to hmFinal

 hmFinal.put("A", hmA);

Now if I create a temp hashmap

HashMap<String, Message> tempHM =  new HashMap<>();

How could I copy the entire hashmap hmA to tempHM using hmFinal if I only had the letter A to search with?

Basically, if a user wants to see the hashmap associated with the letter A, I want to be able to grab all of hmA and search through the info in it.

Upvotes: 0

Views: 298

Answers (2)

dimoniy
dimoniy

Reputation: 5995

The method you're looking for is putAll:

HashMap<String, Message> tempHM =  new HashMap<>();
tempHM.putAll(hmFinal.get("A"));

Upvotes: 3

M A
M A

Reputation: 72854

After retrieving the map by searching using the letter A, use putAll to copy all entries to the map:

HashMap<String, Message> mapA = hmFinal.get("A");
tempHM.putAll(mapA);

P.S.: Try to program variables using the interfaces (Map instead of HashMap).

Upvotes: 3

Related Questions