【问题标题】:How to create a staggering List from a List [duplicate]如何从列表中创建一个惊人的列表 [重复]
【发布时间】:2019-09-20 09:12:50
【问题描述】:

假设我们有一个列表:

[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 流来做到这一点。

有人可以帮忙吗?

【问题讨论】:

  • “我知道如何在 Java 计划中做到这一点” 请出示该代码
  • 计划java代码添加。

标签: java-8 java-stream


【解决方案1】:

好的。我是这样计算的:

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());
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-18
    • 2020-02-27
    • 1970-01-01
    • 2016-05-09
    • 2017-03-30
    • 2019-12-14
    • 2021-06-25
    • 2018-11-21
    相关资源
    最近更新 更多