【问题标题】:Obtaining array element differences in JavaJava中获取数组元素差异
【发布时间】:2013-05-07 09:10:21
【问题描述】:

假设我有两个字符串数组:

String[] first = new String[]{"12","23","44","67"};
String[] second= new String[]{"12","22","46","67"};

我搜索了一个像 PHP 的 array_diff 这样的函数,它会给我这两个数组的区别,如下所示:

{"23","44"}

此操作是否有内置函数,或者我应该创建一个 for 循环并检查差异?

【问题讨论】:

  • 不,没有内置功能。你可以为此创建一个比较器。
  • 与您的问题无关:您应该考虑使用List<String> first = new ArrayList<String>(Arrays.asList("12", "23"); 而不是String[]
  • @MichaWiedenmann Arrays.asList 返回一个List,为什么要将它传递给List 构造函数?其次,根据用例,数组是完全可以接受的数据结构。
  • 如果第二个列表是"12","22","23","67",他的差异是什么?
  • @JohnB 因为这取决于我小心使用“考虑”这个词。同样对于Arrays.asList,返回的列表通过抛出异常来实现List 接口的一些方法(例如add())。我不知道 OP 想要在什么情况下使用字符串,因此选择更灵活的版本。

标签: java arrays string-matching


【解决方案1】:

您可以从这些数组中创建两个 Set,例如:

List<String> firstList = Arrays.asList(first);
List<String> secondList = Arrays.asList(second);

Set<String> firstSet = new HashSet<String>(first);
Set<String> secondSet = new HashSet<String>(second);  

然后使用removeAll方法:

firstSet.removeAll(secondList);
secondSet.removeAll(firstList);

所以现在firstList 包含仅在第一个数组中可用的所有元素,secondList 仅包含在第二个数组中可用的元素。

可以使用以下方法创建仅包含其中一个集合中可用元素(没有两个集合中可用元素)的集合:

new HashSet<String>(firstSet).addAll(secondSet);

【讨论】:

  • 此代码 Set&lt;String&gt; firstSet = new HashSet&lt;String&gt;(first); 给出“Connot resolve constructor Hashset(java.lang.String[])”错误。 Hashset可以这样构造吗?
  • @trante 非常感谢您指出这一点,我已经修复了答案。
【解决方案2】:

Guava 的Sets 类有一个difference 方法。

所以

Set<String> diff = Sets.difference(newHashSet(first), newHashSet(second));

【讨论】:

【解决方案3】:

PHP 数组根本就不是数组,所以才会有这种奇怪的 diff 方法。

如果你想要数学意义上的两组 (A - B) 之间的差异,那么

1) 使用集合

Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();

2) 使用差异法(包含set1中所有不在set2中的元素)

set1.removeAll(set2)

注意,这是不对称的差异。

【讨论】:

  • removeAll 不返回布尔值而不是设置元素吗?
  • @trante 是的。但它也根据set1 - set2修改了set1
猜你喜欢
  • 1970-01-01
  • 2019-10-26
  • 1970-01-01
  • 1970-01-01
  • 2019-11-26
  • 1970-01-01
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多