find non-common elements between two sets of strings

advertisements

There was a problem that is How to find non- common elements between two string arrays. Eg:

String[] a = {"a", "b", "c", "d"};
String[] b = {"b", "c"};
// O/p should be a,d

I have tried the below approach but please advise is there any other efficient way to achieve the same

String[] a = {"a", "b", "c", "d"};
String[] b = {"b", "c"};

Set<String> set = new HashSet<>(a.length);
for (String s : a) {
    set.add(s);
}
for (String s : b) {
    set.remove(s);
}
return set;

please advise is there any other efficient approach also we can achieve this in java


That seems the most effective way using Java. Still, you can make it shorter by using addAll, removeAll and retainAll

String[] a = {"a","b","c","d"};
String[] b = {"b", "c"};

//this is to avoid calling Arrays.asList multiple times
List<String> aL = Arrays.asList(a);
List<String> bL = Arrays.asList(b);

//finding the common element for both
Set<String> common = new HashSet<>(aL);
common.retainAll(bL);

//now, the real uncommon elements
Set<String> uncommon = new HashSet<>(aL);
uncommon.addAll(bL);
uncommon.removeAll(common);
return uncommon;

Running sample: http://ideone.com/Fxgshp