Java – find non-public elements between two arrays

In an interview, people were asked to find unusual elements between two string arrays

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

I answered the question of using hashtable implementation in Java set The code using set is simpler:

String[] a = {"a","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 question is, is there a better way to achieve this goal

Solution

You can shorten the code

TreeSet set = new TreeSet(Arrays.asList(a));
set.removeAll(Arrays.asList(b));

Demo

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>