这个问题已经被问的一个方面forEach
。
评论(答案被接受后):我接受@nullpointer的答案,但它是正确的只是在我的代码示例的情况下,而不是在大约减少的突破能力一般的问题..
问题:
但有一个方式reduce
或collect
以“破发”过早,没有通过所有的流元素回事?(这意味着我需要积累的状态,而迭代,所以我用reduce
或collect
)。
总之:我需要遍历流(元素是整数,从小下令大)的所有元素,但看看到2个相邻元素并加以比较,如果它们之间的差值小于1时,我需要“破发”和一站式“积累状态”,我需要返回最后传递的元素。
变异投掷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 the array will represent the "previous element" while iterating the stream
return new int[]{0, 0};
}
};
//the array in accumulator 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 the array will represent the "previous element" while iterating the stream
ObjIntConsumer<int[]> accumulator = new ObjIntConsumer<int[]>() {
@Override
public void accept(int[] sett, int value) {
if (sett[0] > 0) {
;//do nothing, result is set
} else {
if (sett[1] > 0) {//previous element exists
if (sett[1] + 1 < value) {
sett[0] = sett[1] + 1;
} else {
sett[1] = value;
}
} else {
sett[1] = value;
}
}
}
};
BiConsumer<int[], int[]> combiner = new BiConsumer<int[], int[]>() {
@Override
public void accept(int[] sett1, int[] sett2) {
System.out.println("Combiner is not used, we are in sequence");
}
};
int result[] = Arrays.stream(A).sorted().filter(value -> value > 0).collect(supplier, accumulator, combiner);
return result[0];
}
/**
* We have an input array
* We need order it, filter out all elements that <=0 (to have only positive)
* We need find a first minimal integer that does not exist in the array
* In this example it is 5
* Because 4,6,16,32,67 positive integers array is having 5 like a minimum that not in the array (between 4 and 6)
*
* @param args
*/
public static void main(String[] args) {
int[] a = new int[]{-2, 4, 6, 16, -7, 0, 0, 0, 32, 67};
Solution s = new Solution();
System.out.println("The value is " + s.solution(a));
}
}
给定一个数组作为输入,在我看来,你要找的是这样的:
int stateStream(int[] arr) {
return IntStream.range(0, arr.length - 1)
.filter(i -> arr[i + 1] - arr[i] > 1) // your condition
.mapToObj(i -> arr[i])
.findFirst() // first such occurrence
.map(i -> i + 1) // to add 1 to the point where the cehck actually failed
.orElse(0); // some default value
}
或者划痕,而将其转换为一个排序和筛选值列表如下:
int stateStream(int[] arr) {
List<Integer> list = Arrays.stream(arr)
.boxed().sorted()
.filter(value -> value > 0)
.collect(Collectors.toList());
return IntStream.range(0, list.size() - 1)
.filter(i -> list.get(i + 1) - list.get(i) > 1)
.mapToObj(list::get)
.findFirst()
.map(i -> i + 1)
.orElse(0);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句