Find non-common elements between two string arrays
There was a problem: find not common elements between two string arrays. For example:
String[] a = {"a", "b", "c", "d"};
String[] b = {"b", "c"};
// O/p should be a,d
I tried the approach below, but please advise if there is another 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 if there is another efficient approach and we can achieve this in java
source to share
This seems to be the most efficient way to use Java. However, you can make it shorter by using addAll
, removeAll
andretainAll
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;
Sample launch: http://ideone.com/Fxgshp
source to share
Using Apache Commons Lang3 ArrayUtils library you can do this:
String[] nonCommon = ArrayUtils.addAll(
ArrayUtils.removeElements(a, b),
ArrayUtils.removeElements(b, a));
I can't talk about its efficiency, but it's more efficient to write since it's one line of code and you don't need to create and manage sets.
This approach also captures the individual elements in the array b
, as shown in this Groovy test case
@Grab('org.apache.commons:commons-lang3:3.3.2')
import org.apache.commons.lang3.ArrayUtils
String[] a = ["a", "b", "c", "d"]
String[] b = ["b", "c", "e"]
assert ["a", "d", "e"] == ArrayUtils.addAll(ArrayUtils.removeElements(a, b), ArrayUtils.removeElements(b, a))
source to share
The Apache community collections CollectionUtils
have a disjunction () method that will do exactly what you want.
source to share