3 回答
![?](http://img1.sycdn.imooc.com/54584e1f0001bec502200220-100-100.jpg)
TA贡献1877条经验 获得超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]]
![?](http://img1.sycdn.imooc.com/5458506b0001de5502200220-100-100.jpg)
TA贡献1820条经验 获得超10个赞
如果你使用番石榴,那么这里有一个解决方案:
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'
![?](http://img1.sycdn.imooc.com/54584f240001db0a02200220-100-100.jpg)
TA贡献1801条经验 获得超16个赞
随着轻微的修改到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]]
添加回答
举报