[英]How to perform arithmetic operation in foreach java 8
I am new to java 8 and I tried to write the below code snippet in java 8 but did work.我是 java 8 的新手,我尝试在 java 8 中编写以下代码片段,但确实有效。
static int getMissingNo(int a[], int n) {
int i, total;
total = (n + 1) * (n + 2) / 2;
for (i = 0; i < n; i++)
total -= a[i];
return total;
}
// this is waht i tried in java 8
int total = (n+1) * (n+2) /2;
unicArray.stream().forEach(e->{
total = total - e;
});
The code snippet gives me a compilation error saying local variable should be final but if it is final how can I return that value back代码片段给了我一个编译错误,说局部变量应该是最终的,但如果它是最终的,我该如何返回该值
You can simply return the difference between the total
and the sum
of array as:您可以简单地将数组的
total
与sum
之间的差返回为:
int expectedSum = (n + 1) * (n + 2) / 2;
int actualSum = Arrays.stream(a).sum(); // .distinct().sum() for sum of unique numbers
return expectedSum - actualSum;
Please find the code below:请在下面找到代码:
static List<Integer> getMissingNo(int[] a, int n) {
List<Integer> listOfDistinctElements = Arrays.stream(a)
.boxed()
.distinct().collect(Collectors.toList());
List<Integer> elemntsLeftOut = new ArrayList<>();
IntStream.range(1, listOfDistinctElements.get(listOfDistinctElements.size()-1)).forEach(index ->
{
if(!listOfDistinctElements.contains(index)){
elemntsLeftOut.add(index);
}
});
return elemntsLeftOut;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.