gpt4 book ai didi

java - 值的组序列

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:12:54 25 4
gpt4 key购买 nike

我想知道是否有任何巧妙的方法可以使用新的 Stream API 来“分组”值序列。

例如将一系列整数拆分为整数组,其中每组都是一个递增的数字序列:

IntStream seq = IntStream.of(1, 2, 3, -1, -1, 1, 2, 1, 2);
IntFunction next = i -> i + 1;

// DESIRED OUTPUT: [[1,2,3], [-1], [-1], [1,2], [1,2]]

最佳答案

不幸的是,Stream API 不太适合解决涉及对 Stream 元素的依赖操作的问题,例如这个问题。

但是,您可以使用 StreamEx为此的图书馆:

public static void main(String[] args) {
IntStream seq = IntStream.of(1, 2, 3, -1, -1, 1, 2, 1, 2);
IntUnaryOperator next = i -> i + 1;

List<List<Integer>> result =
IntStreamEx.of(seq).boxed().groupRuns((i1, i2) -> next.applyAsInt(i1) == i2).toList();

System.out.println(result); // prints "[[1, 2, 3], [-1], [-1], [1, 2], [1, 2]]"
}

这将所有连续的整数分组到 List 中,其中第二个整数等于应用于第一个整数的 next 函数。最后,这个 Stream 被收集到一个 List 中。

关于java - 值的组序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35234128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com