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);
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.
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.
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.
You should use the method Map::computeIfAbsent
to create or get the List
:
myMap.computeIfAbsent(MY_KEY, k -> new ArrayList<>()).add(value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With