Reputation: 605
I am trying to write a simple reduce function that will check if all the elements of srcList
are present in targetList
:
List<String> srcList = Arrays.asList("a", "b");
List<String> targetList = Collections.singletonList("a");
Boolean result = srcList.stream().reduce(true
, (prevResult, srcElement) -> targetList.contains(srcElement)
, (prevResult, currentResult) -> prevResult && currentResult);
System.out.println(result); // prints false as expected
The above mentioned lambda does not seem to be working as expected. For instance if we change the element in the target list the result is printed as true:
List<String> srcList = Arrays.asList("a", "b");
List<String> targetList = Collections.singletonList("b");
Boolean result = srcList.stream().reduce(true
, (prevResult, srcElement) -> targetList.contains(srcElement)
, (prevResult, currentResult) -> prevResult && currentResult);
System.out.println(result); // prints true
It looks like that the expression is returning the result of last accumulator
evaluation only (i.e. the contains operation in this case) and the combiner is not performing the &&
on all the results.
Can someone please explain?
Upvotes: 0
Views: 112
Reputation: 140309
The issue is that you ignore prevResult
in the accumulator:
(prevResult, srcElement) -> targetList.contains(srcElement)
should be, for example
(prevResult, srcElement) -> prevResult && targetList.contains(srcElement)
But honestly, it would be easier to use containsAll
:
targetList.containsAll(srcList)
Upvotes: 2