Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more elegant solution for filling a List from a Map? [duplicate]

Tags:

java

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()));
like image 230
schoener Avatar asked Jan 01 '23 00:01

schoener


2 Answers

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.

like image 156
Jacob G. Avatar answered Feb 07 '23 06:02

Jacob G.


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);
like image 38
Jan Avatar answered Feb 07 '23 06:02

Jan