2016-06-22 2 views
1

コード全体を入力する必要はありません(私は不要だと感じています)。私の問題は次のとおりです。私は2つの大きな弦を持っています。 2つのハッシュセットに追加します。それで、私は両方の要素の要素が同じであるかどうかをチェックし、そうでなければ異なる要素を出力したいのです。対応する要素が同じであるため、すべての要素を反復処理する必要がないため、反復処理では作成したくありません。両方のHashSetにない要素を出力する

Set latestStableRevConfigurationSet = new HashSet(Arrays.asList(latestStableRevConfiguration.split(";"))); 
    Set currentRevConfigurationSet = new HashSet(Arrays.asList(currentRevConfiguration.split(";"))); 

    assertTrue(latestStableRevConfigurationSet.containsAll(currentRevConfigurationSet)); 
    assertTrue(currentRevConfigurationSet.containsAll(latestStableRevConfigurationSet)); 

セットが「同じ」であるが、異なる要素を印刷どのようにA-B/B-Aを実装する場合、私はのみアサートすることができる以上のよう?

答えて

1

あなたはグァバを使用することができます。

SetView<Number> difference = com.google.common.collect.Sets.symmetricDifference(set2, set1); 

新しいdependecyを追加したくない場合は、あなたは少しGithubレポで利用可能なコードを変更することができます。

1

すべての要素が1つのセットに収まるようにします。

union.removeAll(intersection); 
:それを行う方法は

Set union = new HashSet(); 
union.addAll(latestStableRevConfigurationSet); 
union.addAll(currentRevConfigurationSet); 

とすべての要素の和を取り、その後、交差点(すなわち共通の要素)

Set intersection = new HashSet(); 
intersection.addAll(latestStableRevConfigurationSet); 
intersection.retainAll(currentRevConfigurationSet); 

を取り、最終的に2を減算することです

+0

それは不必要に複雑です。 2度目のホイールを発明しないでください! – xenteros

+0

だから私はあなたの答えをupvoted!すでにこれを行っているライブラリを使用するほうが良いことに完全に同意しますが、新しい依存関係を(おそらく)導入することなく、それがどのように行われるかを知ることは有用です。 – inovaovao

2

これを試してみてください:

Set<String> latestStableRevConfigurationCopy = new HashSet<>(latestStableRevConfigurationSet); 
    Set currentRevConfigurationCopy = currentRevConfigurationSet; 

    latestStableRevConfigurationCopy.removeAll(currentRevConfigurationSet); 
    currentRevConfigurationCopy.removeAll(latestStableRevConfigurationSet); 

    //this would print all the different elements from both the sets. 
    System.out.println(latestStableRevConfigurationCopy); 
    System.out.println(currentRevConfigurationCopy); 
+0

'currentRevConfigurationCopy'は' currentRevConfigurationSet'のコピーではありません:それは同じセットへの別の参照です! – inovaovao

+0

はい、私は知っています。わかりやすく** currentRevConfigurationCopy **という名前にしました。 –

+0

元の 'currentRevConfigurationSet'が再度使用される場合に備えて変更されていることに注意してください。副作用から安全になるためには、 'latestStableRevConfigurationSet'のようにコピーを取るべきです。 – inovaovao

関連する問題