List<Map<String, Object>>에 item 추가하기

2024. 11. 12. 22:14Java

new를 사용

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // Initialize the list
        List<Map<String, Object>> list = new ArrayList<>();

        // Create a new map
        Map<String, Object> item = new HashMap<>();
        item.put("key1", "value1");
        item.put("key2", 123); // You can add any type of object here

        // Add the map to the list
        list.add(item);

        // Print the list to verify
        System.out.println(list);
    }
}

new를 사용하지 않음(Java 9+ 부터 사용 가능)

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        List<Map<String, Object>> list = new ArrayList<>();

        // Add an item to the list using Map.of
        list.add(Map.of("key1", "value1", "key2", 123));

        // Print the list to verify
        System.out.println(list);
    }
}

2개 혼용

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        List<Map<String, Object>> list = new ArrayList<>();

        // Add multiple key-value pairs using Map.of and make it mutable
        Map<String, Object> item = new HashMap<>(Map.of("key1", "value1", "key2", 123));
        list.add(item);

        // Now the map in the list is mutable
        item.put("key3", "value3");

        System.out.println(list);
    }
}