JAVA

[JAVA] 여러 type 섞인 이중 리스트 List<List<Object>> transpose (전치) 하는 법

고수트 2022. 9. 14. 21:01
반응형

table 모양으로

String 또는 Integer type 등으로 섞인 이중 리스트를 transpose (전치) 하고 싶을때가 있다.

이럴때는 아래와 같이 transpose 함수를 만들어 치환하면 된다.

import java.util.*;
public class MyClass {
    public static void main(String[] args) {
        // Object table 생성
        List<List<Object>> table = new ArrayList<>();
        table.add(new ArrayList<>(Arrays.asList("id", "name", "email")));
        table.add(new ArrayList<>(Arrays.asList(1, "abc", "a@")));
        table.add(new ArrayList<>(Arrays.asList(2, "def", "b@")));
        // 전치전
        System.out.println(table);
        table = transposeTable(table);
        // 전치후
        System.out.println(table);
    }
    
    static List<List<Object>> transposeTable(List<List<Object>> table) {
        List<List<Object>> result = new ArrayList<>();
        int size = table.get(0).size();
        for (int i = 0; i < size; i++) {
            List<Object> column = new ArrayList<>();
            for (List<Object> row : table) {
                column.add(row.get(i));
            }
            result.add(column);
        }
        return result;
    }
}
반응형