使用Java流将ArrayList <integer>转换为Integer [] []

时间:2018-07-17 16:43:02

标签: java java-8 java-stream

我有一个ArrayList,我需要将其转换为2D数组。我需要使用Java流来实现。

private static ArrayList<Integer> GLOBALLIST;
Integer[][] TwoDArray = new Integer[2][8];
GLOBALLIST = Lists.newArrayList(36,40,44,48,52,56,60,64,100,104,108, 112,116,120,124,128);
AtomicInteger counter = new AtomicInteger(0);
        TwoDArray = (Integer[][]) ((GLOBALLIST.stream()
                .collect(Collectors.groupingByConcurrent(it -> counter.getAndIncrement() / 8))
                .values()).toArray(new Integer[2][8]));

这给出了错误,指出无法将ObjectList转换为Integer [] []

3 个答案:

答案 0 :(得分:1)

当您的起点是ArrayList时,即List支持随机访问,例如

ArrayList<Integer> list = new ArrayList<>(Arrays.asList(36,40,44,48,52,56,60,64,100,104,108,112,116,120,124,128,132,136,140,144,149,153,157,161,165,169,173,177));

您可以简单地使用

Integer[][] array = IntStream.range(0, (list.size()+7)/8)
    .mapToObj(ix -> list.subList(ix*=8, Math.min(ix+8,list.size())).toArray(new Integer[0]))
    .toArray(Integer[][]::new);

System.out.println(Arrays.deepToString(array));
[[36, 40, 44, 48, 52, 56, 60, 64], [100, 104, 108, 112, 116, 120, 124, 128], [132, 136, 140, 144, 149, 153, 157, 161], [165, 169, 173, 177]]

答案 1 :(得分:0)

如果您使用番石榴,则此处提供一种解决方案:

ArrayList<Integer> GLOBALLIST;
    GLOBALLIST = Lists.newArrayList(36,40,44,48,52,56,60,64,100,104,108, 112,116,120,124,128,132,136,140,144,149,153,157,161,165,169,173,177);
    int[][] twoDList = Lists.partition(GLOBALLIST,8)
            .stream()
            .map(Ints::toArray)
            .map(a -> Arrays.copyOf(a, 8))
            .toArray(int[][]::new);

我在 gradle 中使用了以下番石榴依赖项:
编译'com.google.guava:guava:22.0'

答案 2 :(得分:0)

只需对this answer中的(C:\Data\myfile.xml)进行一些修改,就可以这样做:

blockCollector

测试

public static Integer[][] toArray2D(Collection<Integer> list, int blockSize) {
    return list.stream()
               .collect(blockCollector(blockSize))
               .stream()
               .map(sublist -> sublist.toArray(new Integer[sublist.size()]))
               .toArray(length -> new Integer[length][]);
}
public static <T> Collector<T, List<List<T>>, List<List<T>>> blockCollector(int blockSize) {
    return Collector.of(
            ArrayList<List<T>>::new,
            (list, value) -> {
                List<T> block = (list.isEmpty() ? null : list.get(list.size() - 1));
                if (block == null || block.size() == blockSize)
                    list.add(block = new ArrayList<>(blockSize));
                block.add(value);
            },
            (r1, r2) -> { throw new UnsupportedOperationException("Parallel processing not supported"); }
    );
}

输出

List<Integer> list = Arrays.asList(36,40,44,48,52,56,60,64,100,104,108, 112,116,120,124,128,132,136,140,144,149,153,157,161,165,169,173,177);
Integer[][] r = toArray2D(list, 8);
System.out.println(Arrays.deepToString(r));