JAVA

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

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

table 모양으로

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

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

import java.util.*;
public class MyClass {
    public static void main(String[] args) {
    	// table 생성
        List<List<Integer>> table = new ArrayList<>();
        table.add(new ArrayList<>(Arrays.asList(1, 2, 3)));
        table.add(new ArrayList<>(Arrays.asList(4, 5, 6)));
        table.add(new ArrayList<>(Arrays.asList(7, 8, 9)));
        
        // 전치전
        System.out.println(table);

        table = transposeTable(table);
        // 전치후
        System.out.println(table);
    }
    
    static List<List<Integer>> transposeTable(List<List<Integer>> table) {
        List<List<Integer>> result = new ArrayList<>();
        int size = table.get(0).size();
        for (int i = 0; i < size; i++) {
            List<Integer> column = new ArrayList<>();
            for (List<Integer> row : table) {
                column.add(row.get(i));
            }
            result.add(column);
        }
        return result;
    }
}
반응형