【问题标题】:find non- common elements between two string arrays查找两个字符串数组之间的非公共元素
【发布时间】:2014-08-29 14:23:02
【问题描述】:

有一个问题是如何在两个字符串数组之间找到不常见的元素。例如:

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<String> set = new HashSet<>(a.length);
for (String s : a) {
    set.add(s);
}
for (String s : b) {
    set.remove(s);
}
return set;

请告知是否有任何其他有效的方法,我们也可以在 java 中实现这一点

【问题讨论】:

  • 在上面的示例中,ba 的子集。如果不是这种情况,您期望什么输出?
  • java67.blogspot.de/2014/05/… 阅读此内容,您将找到您需要做的事情。
  • 鉴于您所说的问题,您的解决方案不正确。如果 "e" 在 string[] b 中怎么办?

标签: java


【解决方案1】:

这似乎是使用 Java 最有效的方式。不过,您可以使用addAllremoveAllretainAll 使其更短

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;

运行示例:http://ideone.com/Fxgshp

【讨论】:

  • 这和题中使用的方法有区别吗?
  • @mohaned 这似乎是使用 Java 最有效的方式。 不过,您可以缩短它
  • 我知道它更短,但它更有效吗?
  • @mohaned 是一样的,只是代码更少......这就是为什么我用我的答案的第一部分来回答你的问题。
【解决方案2】:

使用 Apache Commons Lang3 库的 ArrayUtils,您可以这样做:

String[] nonCommon = ArrayUtils.addAll(
        ArrayUtils.removeElements(a, b), 
        ArrayUtils.removeElements(b, a));

我无法谈论它的性能效率,但它编写起来更高效,因为它是一行代码,您不需要创建和操作 Set。

这种方法也可以捕获数组 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))

【讨论】:

【解决方案3】:

Apache Commons Collections CollectionUtils 有一个名为 disjunction() 的方法,可以完全满足您的需求。

【讨论】:

    猜你喜欢
    • 2015-07-20
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    相关资源
    最近更新 更多