Saturday, 2 July 2016

Allowing Map To Accept Duplicate Key's Value !!

Allowing Map To Accept Duplicate Key's Value !!


Q: Map map = new HashMap();
     map.put("sunil", "56");
     map.put("sunil", "78");
     System.out.println(map);

O/p : {sunil=78}

So How we can make map to accept duplicate key's  value? i.e  O/p be Like : {sunil=[56, 78]} ?

Ans:

1. We have to create our own Map implemented class Extending LinkedHashMap.
   
     Take Key type as String.
     Take Value type as List.

Example: public class MapCheckDuplicateKeyAccept extends LinkedHashMap<String, List<String>>


2. Override put() method in the Class.

Example:

package com.test.practice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class MapCheckDuplicateKeyAccept extends LinkedHashMap<String, List<String>> {

public void put(String key, String number){

List l = get(key);
if(l==null){
l = new ArrayList<>();
super.put(key, l);
}
l.add(number);
}

public static void main(String[] args) {

MapCheckDuplicateKeyAccept map = new MapCheckDuplicateKeyAccept();
map.put("sunil", "56");
map.put("sunil", "78");

System.out.println(map);
}

}

No comments:

Post a Comment