这个问题是在 的背景下提出的forEach
。
评论(答案被接受后):我接受了@nullpointer的答案,但它仅在我的代码示例的上下文中才是正确的,而不是在关于reduce的可破坏性的一般问题中。
问题:
但是有没有一种方法可以reduce
在collect
不遍历所有流元素的情况下提前“中断”?(这意味着我需要在迭代时累积状态,所以我使用reduce
或collect
)。
简而言之:我需要迭代流的所有元素(元素是整数并从小到大排序),但是查看 2 个相邻元素并比较它们,如果它们之间的差异大于 1,我需要“中断”并停止“累积状态”,我需要返回最后传递的元素。
抛出 a 的变体RuntimeException
和传递外部状态的变体 - 对我来说不好。
带注释的代码示例:
public class Solution {
public int solution(int[] A) {
Supplier<int[]> supplier = new Supplier<int[]>() {
@Override
public int[] get() {
//the array describes the accumulated state:
//first element in the array , if set > 0, means - the result is achieved, we can stop iterate over the rest elements
//second element in …
Run Code Online (Sandbox Code Playgroud) val set1 = Set(1,2,3)
Run Code Online (Sandbox Code Playgroud)
要么
val list1 = List(1,2,3)
Run Code Online (Sandbox Code Playgroud)
你能描述这些物体构造背后的精确机制吗?
在Java中,我们需要HashSet或LinkedList来构造对象.
在这里,我们看到与apply方法一起使用的特征?
这适用于哪种方法?
带有暗示的东西?