Java List Transpose transpose(List> input)

Here you can find the source of transpose(List> input)

Description

transpose

License

Open Source License

Declaration

public static List<List<?>> transpose(List<List<?>> input) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;
import java.util.Collection;

import java.util.Iterator;
import java.util.List;

public class Main {
    public static List<List<?>> transpose(List<List<?>> input) {
        Object[][] matrix = new Object[input.size()][];
        int max = 0;
        for (Iterator<List<?>> i = input.iterator(); i.hasNext();) {
            List<?> a = i.next();
            max = Math.max(max, a.size());
        }//from   ww w  .  j a v a 2 s  .  c om
        for (int i = 0; i < input.size(); i++) {
            List<?> a = input.get(i);
            matrix[i] = new Object[max];
            a.toArray(matrix[i]);
        }
        List<List<?>> output = new ArrayList<List<?>>();
        for (int i = 0; i < matrix[0].length; i++) {
            List<Object> a = new ArrayList<Object>();
            for (int j = 0; j < matrix.length; j++)
                if (matrix[j][i] != null)
                    a.add(matrix[j][i]);
            output.add(a);
        }
        return output;
    }

    public static long max(long[] arr) {
        if (arr.length == 0)
            return 0;
        long ret = arr[0];
        for (int i = 1; i < arr.length; i++)
            if (arr[i] > ret)
                ret = arr[i];
        return ret;
    }

    public static int max(int[] arr) {
        if (arr.length == 0)
            return 0;
        int ret = arr[0];
        for (int i = 1; i < arr.length; i++)
            if (arr[i] > ret)
                ret = arr[i];
        return ret;
    }

    /**
     * @param arr
     * @param oid
     * @return
     */
    public static Object get(Collection<?> arr, int idx) {
        if (idx < 0)
            return null;
        for (Iterator<?> i = arr.iterator(); i.hasNext(); idx--) {
            Object b = i.next();
            if (idx <= 0)
                return b;
        }
        return null;
    }
}

Related

  1. transpose(List> matrix)
  2. transpose(List> matrix)
  3. transpose(List> table)