如何从列表创建交错列表

时间:2019-05-01 20:36:32

标签: java-8 java-stream

假设我们有一个列表:

[1,2,3,4,5,6,7]

对于给定的长度,例如3,我想创建一个包含以下内容的列表列表:

[1,2,3]
[2,3,4]
[3,4,5]
...

子列表中的元素数是指定的长度(3)。

我知道如何在计划Java中做到这一点:

List<List<Integer>> function(List<Integer> s, int m) {
    if(s.size() < m) throw new IllegalArgumentException();
    List<List<Integer>> result = new ArrayList<>();
    for(int i = 0 ; i < s.size() - m + 1 ; i ++) {
        List<Integer> sub = s.subList(i, i+m);
        result.add(sub);
    }
    return result;
}

但是我想知道如何使用Java 8流。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

好。我这样算出来:

List<List<Integer>> function(List<Integer> s, int m) {
     return IntStream.range(0, s.size() - m + 1).mapToObj(index -> s.subList(index, index + m)).collect(Collectors.toList());
}

我的测试表明它是正确的。但是有更好的解决方案吗?