我有一段使用传统的for循环编写的代码,如下所示。我想将其重构为使用Java 8流并删除for循环。以下代码的输出应为3,因为这是最长的连续数字列表(4、5和6)

    List<Integer> weekDays = Lists.newArrayList(1, 2, 4, 5, 6);

    List<Integer> consecutiveIntervals = Lists.newArrayList();
    int maxConsecutiveTillNow = 1;
    for (int i = 1; i < weekDays.size(); i++) {
        if (weekDays.get(i) - weekDays.get(i - 1) == 1) {
            maxConsecutiveTillNow++;
        } else {
            consecutiveIntervals.add(maxConsecutiveTillNow);
            maxConsecutiveTillNow = 1;
        }
    }
    consecutiveIntervals.add(maxConsecutiveTillNow);

    System.out.println(consecutiveIntervals.stream()
                                           .max(Integer::compareTo)
                                           .get()
                      );

最佳答案

Stream API不适用于此类问题。几乎不可能以正确的方式跟踪Stream的可见元素。因此,您必须使用多个Streams。基于Stuart Marks'答案之一。

List<Integer> weekDays = Arrays.asList(1, 2, 4, 5, 6);
int[] indices = IntStream.rangeClosed(0, weekDays.size())
   .filter(i -> i == 0 || i == weekDays.size() || weekDays.get(i - 1) + 1 != weekDays.get(i))
   .toArray();
int longest = IntStream.range(0, indices.length - 1).map(i -> indices[i + 1] - indices[i])
   .max().orElseThrow(NoSuchElementException::new);
System.out.println(longest);

输出量

3

10-07 19:08