List<Map<String, Object>>에서 특정 컬럼을 List로 뽑아내기

2024. 11. 7. 22:37Java

row.get("name")에서 형변환을 잘해줘야 함

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

public class ColumnExtractor {
    public static void main(String[] args) {
        List<Map<String, Object>> data = new ArrayList<>();
        data.add(Map.of("id", 1, "name", "Alice", "age", 25));
        data.add(Map.of("id", 2, "name", "Bob", "age", 30));
        data.add(Map.of("id", 3, "name", "Charlie", "age", 35));

        // Extract a list of values from the "name" column
        List<Object> names = data.stream()
                                 .map(row -> row.get("name"))
                                 .collect(Collectors.toList());

        System.out.println("Names: " + names);
    }
}