Efficient way to divide a list into lists of n size

前端 未结 14 1280
无人共我
无人共我 2020-11-27 16:59

I have an ArrayList, which I want to divide into smaller Lists of n size, and perform an operation on each. My current method of doing this is

implemented with Array

14条回答
  •  独厮守ぢ
    2020-11-27 17:35

    // Testing data

    List list = Arrays.asList(0, 1, 2,     3, 4, 5,    6, 7, 8,    9);
    int n = 3;
    

    // One line(statement) with java 8 stream and list.subList

    List> partitions = IntStream.range(0, list.size())
        .filter(i -> i % n == 0)
        .mapToObj(i -> list.subList(i, Math.min(i + n, list.size() )))
        .collect(Collectors.toList());
    

提交回复
热议问题