A problem occurred while the Java project was in progress, so I asked a question.
For example, suppose we have this Object in JavaScript.
JavaScript
x
let testObject = {
'Fruit' : [],
'Food': []
}
I can add a value to the food array.
JavaScript
testObject['Fruit'].push('tomato');
testObject['Food'].unshift('ramen');
Like javascript, java directly pushes a value to a list of objects.
JavaScript
HashMap<String, ArrayList<String>> testObject = new HashMap<>();
testObject.put("Food",new ArrayList<>());
testObject.put("Fruit",new ArrayList<>());
for(T etc : testObject ){
if(etcequals("Fruit")){
etc..add('tomato');
}else if(etc..equals("Food")){
etc..add('ramen');
}
}
Is there any way other than to declare ArrayList in advance using call by reference and put it in testObject?
Advertisement
Answer
As of java 8+ you can try something like this:
JavaScript
Map<String, Collection<String>> food = new HashMap<>();
// ... any code ...
food.computeIfAbsent("fruits", k -> new ArrayList<String>()).add("apple");