找到两个字符串数组之间的非常见元素
有一个问题是如何在两个字符串数组之间找到非常见元素。 例如:
String[] a = {"a", "b", "c", "d"}; String[] b = {"b", "c"}; // O/p should be a,d
我已经尝试了以下方法,但请告知是否有任何其他有效的方法来实现相同
String[] a = {"a", "b", "c", "d"}; String[] b = {"b", "c"}; Set set = new HashSet(a.length); for (String s : a) { set.add(s); } for (String s : b) { set.remove(s); } return set;
请指教是否有任何其他有效的方法我们也可以在java中实现这一点
这似乎是使用Java的最有效方式。 不过,您可以使用addAll
, removeAll
和retainAll
缩短它
String[] a = {"a","b","c","d"}; String[] b = {"b", "c"}; //this is to avoid calling Arrays.asList multiple times List aL = Arrays.asList(a); List bL = Arrays.asList(b); //finding the common element for both Set common = new HashSet<>(aL); common.retainAll(bL); //now, the real uncommon elements Set uncommon = new HashSet<>(aL); uncommon.addAll(bL); uncommon.removeAll(common); return uncommon;
运行示例: http : //ideone.com/Fxgshp
使用Apache Commons Lang3库的ArrayUtils ,您可以这样做:
String[] nonCommon = ArrayUtils.addAll( ArrayUtils.removeElements(a, b), ArrayUtils.removeElements(b, a));
我不能说它的性能效率,但它更有效率,因为它是一行代码,你不需要创建和操作集。
这种方法也捕获了数组b
不同元素,如Groovy测试用例所示
@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))
Apache Commons Collections CollectionUtils
有一个名为disjunction()的方法,可以完全按照你想要的方式执行。