I try to fill the List from the Map. In case the list is NULL
I will create a new List and add a new created element otherwise add this element to existing list.
I'm wondering if there is a more elegant solution in JAVA8 for this. Any help appreciated.
Map<String, List<MyObject>> myMap = new HashMap<>();
List<MyObject> list = myMap.get("key");
myMap.put("key", list == null ? Arrays.asList(new MyObject()) : Arrays.asList(list, new MyObject()));
Assuming Arrays.asList(list, new MyObject())
should instead add a new MyObject
instance to list
, then yes, you can use Map#computeIfAbsent
to make the code more readable:
Map<String, List<MyObject>> myMap = new HashMap<>();
myMap.computeIfAbsent("key", key -> new ArrayList<>()).add(new MyObject());
If "key"
is not present as a key in the Map
, then a mapping will be created to a new ArrayList
instance (which is returned). Otherwise, the existing List
will be returned by the call to computeIfAbsent
, allowing you to add a new element to it.
You could simply make sure your get doesn't return null in the first place:
List<MyObject> list = myMap.getOrDefault("key", new ArrayList<>);
Then you'll end up with
List<MyObject> list = myMap.getOrDefault("key", new ArrayList<>);
list.add(new MyObject());
myMap.put("key", list);
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