Test if two sets share 3 elements with Java streams
You could use simply Set.retainAll(Collection)
:
setOne.retainAll(setTwo);
boolean isMoreTwo = setOne.size() > 2
If you don't want to modify setOne
, create a new instance of the Set :
Set<Integer> newSetOne = new HashSet<>(setOne)
newSetOne.retainAll(setTwo);
boolean isMoreTwo = newSetOne.size() > 2
Note that all ways actually shown to solve your need (in your question, my answer and that one of Naman) are not correct way to perform an assertion in an unit test.
An assertion should produce a useful error message if the assertion fails.
So that will really not help you since a boolean is true or false and that's all :
Assertions.assertEquals(true,testSets(setOne,setTwo));
Besides, it should also be written rather like :
Assertions.assertTrue(testSets(setOne,setTwo));
To achieve your requirement, you should count the number of matching elements between the sets and stopping it as soon as you reach the desired target.
long nbMatchLimitedToThree = setOne.stream().filter(setTwo::contains).limit(3).count();
Assertions.assertEqual(3, nbMatchLimitedToThree, "At least 3 matches expected but actually only " + nbMatchLimitedToThree +". setOne=" + setOne + ",setTwo=" + setTwo);
That is more performant and that is a correct way to write unit tests.
Use Stream.count
as
private boolean testSets(Set<Integer> setOne, Set<Integer> setTwo) {
return setOne.stream().filter(setTwo::contains).count() > 2;
}
or to add to it, avoiding to iterate through the complete set if more than two elements are found early, use limit
as:
return setOne.stream().filter(setTwo::contains).limit(3).count() > 2;
guava makes this very easy to read:
private boolean testSets( Set<Integer> setOne, Set<Integer> setTwo ) {
return Sets.intersection(setOne, setTwo).size() > 2;
}