Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find non- common elements between two string arrays

Tags:

java

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

like image 906
user3875672 Avatar asked Jul 20 '26 14:07

user3875672


1 Answers

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

like image 58
Luiggi Mendoza Avatar answered Jul 22 '26 06:07

Luiggi Mendoza