ZAK ZAK:
2セットは、少なくとも3つの共通の要素を持っている場合、私は、テストにJavaストリームの操作を必要としています。
ここでは罰金を作品に私のJava 7のコードは次のとおりです。
@Test
public void testContainement(){
Set<Integer> setOne = IntStream.of(0,1,4,3)
.boxed()
.collect(Collectors.toCollection(HashSet::new));
Set<Integer> setTwo = IntStream.of(0,1,4,5)
.boxed()
.collect(Collectors.toCollection(HashSet::new));
Assertions.assertEquals(true,testSets(setOne,setTwo));
}
private boolean testSets( Set<Integer> setOne, Set<Integer> setTwo ) {
int counter=0;
for (int x: setOne){
if (setTwo.contains(x))
counter++;
}
return counter > 2;
}
どのように我々は、Javaストリーム操作でそれを行うことができますか?
davidxxx:
あなたは、単に使用することができますSet.retainAll(Collection)
:
setOne.retainAll(setTwo);
boolean isMoreTwo = setOne.size() > 2
あなたが変更したくない場合はsetOne
、設定の新しいインスタンスを作成します。
Set<Integer> newSetOne = new HashSet<>(setOne)
newSetOne.retainAll(setTwo);
boolean isMoreTwo = newSetOne.size() > 2
実際に(あなたの質問、私の答えとナマンの1つに)あなたの必要性を解決するために示したすべての方法は、ユニットテストでアサーションを実行するための正しい方法ではないことに注意してください。
アサーションが失敗した場合、アサーションは便利なエラーメッセージを生成する必要があります。
ブール値がtrueまたはfalseで、それがすべてですので、本当にあなたを助けにはなりませんそれはそう。
Assertions.assertEquals(true,testSets(setOne,setTwo));
また、それはまた、かなりのように記述する必要があります。
Assertions.assertTrue(testSets(setOne,setTwo));
あなたの要件を実現するには、セット間の要素を照合して、所望の標的に到達するとすぐにそれを止めるの数をカウントする必要があります。
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);
それは、よりパフォーマンスであり、それは、ライトユニットテストに正しい方法です。