问题描述
我是Java 8流的新手,我无法从嵌套循环操作总和中获得正确的输出。
I am new to Java 8 streams, I am unable to get the correct output from the nested loop operational sum.
在嵌套循环中,我正在调用返回整数的方法;通过这样做最终总结得到的总数
In the nested loop, I am calling a method which is returning an integer; by this doing finally summing up the resultant total
这就是我试过的:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class NestedLoop {
public void callTask(int i, int j) {
System.out.println("i:"+i+"j:"+j);
}
public int getCount(Count count, String j) {
if(count.getCount() >= 123 && count.getCount() <= 125) {
System.out.println("###");
return 1;
}
else {
return 0;
}
}
public static void main(String[] args) {
List<Count> list2 = new ArrayList<>();
List<String> list1 = new ArrayList<>();
Count count = new Count(121);
Count count1 = new Count(122);
Count count2 = new Count(123);
Count count3 = new Count(124);
Count count4 = new Count(125);
list2.add(count4);
list2.add(count2);
list2.add(count3);
list2.add(count1);
list2.add(count);
NestedLoop loop = new NestedLoop();
list1.add("list2 - Op1");
list1.add("list2 - Op2");
list1.add("list2 - Op2");
list1.add("list2 - Op2");
int _count = 0;
IntStream res = list2.parallelStream().flatMapToInt(x -> IntStream.of(list1.stream().mapToInt(y-> loop.getCount(x,y)).sum()));
System.out.println(res.sum());
}
}
Count class
class Count {
private int count;
public Count(int count) {
super();
this.count = count;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
由此,我得到12而不是2.
By this, I am getting 12 instead of 2.
帮助,我代码有问题。
推荐答案
请先干掉代码并先看看,因为12是正确的答案。对于 list2
中的每个元素,您迭代 list1
,然后调用 getCount
,总结值。对于值123,它被称为4次,相同的是124和125.每次返回1,将它们相加所有1 * 3 * 4得到12.为什么你需要2?理由是什么?
Please dry run the code and see first, because 12 is the correct answer. For each element in list2
you iterate list1
and then call the getCount
, summing the values. For the value 123 it is called 4 times, same for 124 and 125. Each returns 1, summing them all 1 * 3 * 4 yields 12. Why you need 2? What is the rationale?
无论如何,这是你要求的吗?根据您的 if
语句,这仍然会产生3。
Anyway is this what you are asking for? This still yields 3, based on your if
statement.
int sum = list2.stream()
.mapToInt(x -> list1.stream().map(y -> loop.getCount(x, y)).findAny().orElse(0))
.sum();
但是,现有的产生12的解决方案可以进一步简化,
However, your existing solution which yields 12, can further be simplified like so,
int sum = list2.stream()
.flatMapToInt(x -> list1.stream().mapToInt(y -> loop.getCount(x, y)))
.sum();
这篇关于如何从嵌套流中获取总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!