Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add value to List inside Map<String, List> in Java 8 [duplicate]

Tags:

Is there a better way in Java 8 to add a value to a List inside of a Map?

In java 7 i would write:

Map<String, List<Integer>> myMap = new HashMap<>(); ... if (!myMap.containsKey(MY_KEY)) {     myMap.put(MY_KEY, new ArrayList<>()); } myMap.get(MY_KEY).add(value);          
like image 609
tak3shi Avatar asked Jan 25 '17 20:01

tak3shi


People also ask

Can we insert duplicate values in Map?

Duplicate keys are not allowed in a Map. Basically, Map Interface has two implementation classes HashMap and TreeMap the main difference is TreeMap maintains an order of the objects but HashMap will not. HashMap allows null values and null keys. Both HashSet and HashMap are not synchronized.

Can Java Map have duplicate values?

Points to remember: Map doesn't allow duplicate keys, but it allows duplicate values. HashMap and LinkedHashMap allows null keys and null values but TreeMap doesn't allow any null key or value. Map can't be traversed so you need to convert it into Set using keySet() or entrySet() method.

How do you add a value to a string object on a Map?

The standard solution to add values to a map is using the put() method, which associates the specified value with the specified key in the map.


1 Answers

You should use the method Map::computeIfAbsent to create or get the List:

myMap.computeIfAbsent(MY_KEY, k -> new ArrayList<>()).add(value); 
like image 99
Flown Avatar answered Oct 12 '22 11:10

Flown