简体   繁体   中英

How to dynamically add multiple values to a single key in HashMap?

I want to add multiple card values to a distinct single key in HashMap at run time if i give an input like this

s 2 
d 5 
s 3 
d 7 
s 4 

it should give an output like

s 2 3 4 
d 5 7

Hint: For this you need to use ArrayList as values and String as keys in HashMap . Here is an example:

HashMap<String, ArrayList<Integer>> myMap = new HashMap<>();
ArrayList<Integer> list = new ArrayList<>();
list.add(2);
list.add(3);
list.add(4);
myMap.put("s", list);

If there are n key, then to dynamically add values to each key, you can do following:

//1. Get the value (list here) for the key you want to add new values. 

ArrayList<Integer> myList =  myMap.get("s");

//2. Check if myList is null
if(myList==null){
    myList = new ArrayList<Integer>();
}

//3. Now add the values to this list.


myList.add(5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM