JAVA

[JAVA] List<List<String>> 이중 리스트 transpose (전치) 하는 법

고수트 2022. 9. 14. 20:49
반응형

table 모양으로

String type으로 적힌 이중 리스트를 transpose (전치) 하고 싶을때가 있다.

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

import java.util.*;
public class MyClass {
    public static void main(String[] args) {
    	// table 생성
        List<List<String>> 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<String>> transposeTable(List<List<String>> table) {
        List<List<String>> result = new ArrayList<>();
        int size = table.get(0).size();
        for (int i = 0; i < size; i++) {
            List<String> column = new ArrayList<>();
            for (List<String> row : table) {
                column.add(row.get(i));
            }
            result.add(column);
        }
        return result;
    }
}
반응형