aleksy.t
aleksy.t

Reputation: 277

printing out elements that are not in both HashSets

I don't want to enter the whole code (I feel it's unnecessary). My problem is: I have two big strings that I split by ';' and add to two Hashsets. Having that, I want to check if the elements of both sets are the same and if they're not - print out different elements. I don't want to make it by any iteration because the corresponding elements are to be the same so there's no need to iterate through every element.

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

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

The way above I can only assert if the sets are 'the same' but how to implement a A-B/B-A so printing out different elements?

Upvotes: 1

Views: 297

Answers (3)

xenteros
xenteros

Reputation: 15852

You can use Guava:

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

If you don't want to add new dependecy, you can slightly modify code available on Github repo.

Upvotes: 1

Pooja Dubey
Pooja Dubey

Reputation: 84

Try this:

    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 );

Upvotes: 2

Nicola Ambrosetti
Nicola Ambrosetti

Reputation: 2504

You want all the elements that are only in one set. A way to do that is to take the union of all the elements with

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

and then take the intersection (i.e. the common elements)

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

and finally subtract the two:

union.removeAll(intersection);

Upvotes: 1

Related Questions