In an interview it was asked 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 answered to the question that in Java Set is implemented using HashTable. The code with Set is much simpler:
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;
now my query is that is there any other better approach to achieve this
You can shorten the code by
TreeSet set = new TreeSet(Arrays.asList(a));
set.removeAll(Arrays.asList(b));