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);
if you don't wanna get your hands dirty and instead rely on bulletproof 3rd party library classes check the following classes, that should do the work:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/MultiValueMap.html
https://google.github.io/guava/releases/21.0/api/docs/com/google/common/collect/Multimap.html
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.