Home > front end >  How to insert duplicate values in map
How to insert duplicate values in map

Time:01-03

I have below list which contain values

List<Customer> list = new ArrayList<>();

list.add( new Customer("ram","Mumbai",1234));

list add(new Customer ("veer","Mumbai",8467));

list.add(new Customer ("jai","Delhi",5242))

I have to iterate this list and insert in map in such a way that address is key and customer object should come as value for map, but problem is, for the same key if we insert duplicate value it is overriding existing values, how can I insert object instead of replace,

Map<String, Customer> map = new HashMap<>();

Looking for inputs, thanks in advance.

CodePudding user response:

You can't have duplicate keys in a Map. You can rather create a Map<Key, List<Value>>, or if you can, use Guava's Multimap. And then you can get the java. util.

Map<String, List<String>> map = new HashMap<>();map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value1");map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value2"); assertThat(map.get("key1").get(0)).isEqualTo("value1");assertThat(map.get("key1").get(1)).isEqualTo("value2");

CodePudding user response:

You can't insert duplicate keys in map but you can insert duplicate values with keys different.

CodePudding user response:

Start with changing the map from Map<String, Customer> map = new HashMap<>(); to Map<String, List<Customer>> map = new HashMap<>();

iterate this list and insert in map in such a way that address is key and customer object should come as value for map

yes, your approach to this is fine.

for (Customer customer : list) {
    if (map.containsKey(customer.getCity())) { // check if the key exists
        map.get(customer.getCity()).add(customer); // add the customer in the existing value list
    } else {
        List<Customer> customers = new ArrayList<>(); // new list
        customers.add(customer);
        map.put(customer.getCity(), customers); // insert current <key,<value>> as the key doesn't exists.
    }
}
  • Related