Skip to content
Advertisement

How to push value in List of Object?

A problem occurred while the Java project was in progress, so I asked a question.

For example, suppose we have this Object in JavaScript.

let testObject = {
   'Fruit' : [],
   'Food': []
}

I can add a value to the food array.

testObject['Fruit'].push('tomato');
testObject['Food'].unshift('ramen');

Like javascript, java directly pushes a value to a list of objects.

        HashMap<String, ArrayList<String>> testObject = new HashMap<>();
        testObject.put("Food",new ArrayList<>());
        testObject.put("Fruit",new ArrayList<>());
        for(T etc : testObject...){
            if(etc...equals("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:

Map<String, Collection<String>> food = new HashMap<>();

// ... any code ...

food.computeIfAbsent("fruits", k -> new ArrayList<String>()).add("apple");
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement