-
冉冉说
当您的起点是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]]
-
拉莫斯之舞
如果你使用番石榴,那么这里有一个解决方案: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 中使用了以下 guava 依赖项:compile 'com.google.guava:guava:22.0'
-
侃侃尔雅
随着轻微的修改到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));输出[[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]]