How to split array list into equal parts?

前端 未结 9 1320
攒了一身酷
攒了一身酷 2020-11-29 07:20

Is there anyway to split ArrayList into different parts without knowing size of it until runtime? I know there is a method called:

list.subList(a,b);
         


        
9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 08:04

    Java 8 (not that it has advantages):

    List list = new ArrayList<>();
    Collections.addAll(list,  "a","b","c","b","c","a","c","a","b");
    

    Grouping size:

    final int G = 3;
    final int NG = (list.size() + G - 1) / G;
    

    In old style:

    List> result = new ArrayList(NG);
    IntStream.range(0, list.size())
        .forEach(i -> {
            if (i % G == 0) {
                result.add(i/G, new ArrayList<>());
            }
            result.get(i/G).add(list.get(i));
        });
    

    In new style:

    List> result = IntStream.range(0, NG)
        .mapToObj(i -> list.subList(3 * i, Math.min(3 * i + 3, list.size())))
        .collect(Collectors.toList());
    

    Thanks to @StuartMarks for the forgotten toList.

提交回复
热议问题