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?
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();
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();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…