public Map<String, List<String>> getContactMap() {
Set<String> keys = contactMap.keySet(); //Get Key Set
for(String key: keys){
List<String> a=contactMap.get(key); //Get List for each Key
a.forEach(System.out::println); //Print the list
}
return null;
}
I have a Hashmap, with multiple values for a single key. I am using this code to print those values, but this does not seem to work. What am I doing wrong?
I am only getting the last inserted value as output.
This is my addContact method:
private Map<String, List<String>> contactMap = new HashMap<String, List<String>>();
@Override
public void addContact(String name, List<String> list) {
// TODO Auto-generated method stub
contactMap.put(name, list);
}
And this is my main():
List <String> list= new ArrayList<String>();
list.add("0321564988");
list.add("7891268429");
contacts.addContact("Name1",list);
list.clear();
list.add("1891219122");
list.add("9495198929");
contacts.addContact("Name2",list);
list.clear();
list.add("8949219912");
contacts.addContact("Name3",list);
This is my desired output:
Name1 Phone1
Phone2
Phone3
Name2 Phone1
Phone2
.....
contactMap.contactMap.put(name, list);is exactly not okay - it will replace the value each time. You need something likecontactMap.computeIfAbsent(name, k -> new ArrayList<>()).add(value). Further, looping over keys and retrieving each value is an anti-pattern, use theentrySet,contactMap.forEach((key, a) -> a.forEach(System.out::println));