有效地比较两个ArrayLists的内容

时间:2016-10-26 05:47:17

标签: java arraylist collections

任何想法为什么contains无法在此工作,这些陈述始终在评估 false firstSchema.contains(firstSchema.get(0))

    List<String> firstSchema = new ArrayList<String>();
    firstSchema.add(0,"test");
    firstSchema.add(1,"testy");

    if(!(firstSchema.contains(firstSchema))){
        System.out.println("hey arraylist content matched");
    }

如果一个arraylist中的任何一个或多个或所有元素与其他arraylist元素匹配,我需要得到真实

5 个答案:

答案 0 :(得分:2)

检查列表是否包含其他列表中的任何元素的最简单方法是在其中一个列表上调用contains(),依次将每个元素作为参数传递。类似的东西:

public <E> boolean slowListContains(List<E> a, List<E> b) {
  for (E element : a) {
    if (b.contains(element)) {
      return true;
    }
  }
  return false;
}

这很慢,因为contains()是线性操作(O(n)),因为我们在循环中调用它,slowListContains()函数需要二次时间({{ 1}})这是穷人。我们可以做得更好。

Set(或者更准确地说是基于散列的集合,例如HashSet)具有高效O(n^2)方法,该方法在不到线性的时间内运行(在这种情况下为常量时间) contains())。将一个或另一个列表转换为HashSet将使Set中的循环更快。类似的东西:

slowListContains()

这并不完美,但肯定比天真的解决方案快得多。稍微改进就是始终将较小的列表转换为public <E> boolean fasterListContains(List<E> a, List<E> b) { Set<E> aSet = new HashSet<>(); aSet.addAll(a); for (E element : b) { if (aSet.contains(b)) { return true; } } return false; } ,而不是第一个。Set。您还可以使用任意Iterable参数而不是List参数,然后检查其中任何一个是Set,如果是,请跳过设置构建步骤。

答案 1 :(得分:2)

您的if(!(firstSchema.contains(firstSchema)))循环错误。您正试图在列表中找到匹配项。您无法检查列表是否包含自身。 从下面的java doc是如何包含作品

  Returns <tt>true</tt> if this list contains the specified element.
  More formally, returns <tt>true</tt> if and only if this list contains
  at least one element <tt>e</tt> such that
  <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.

答案 2 :(得分:1)

您正在检查错误。请参阅firstSchema.contains(firstSchema)错误arrayList.contains(arrayList)无法正常工作。

其次(firstSchema.contains("test"))返回true,因为数组列表包含test!否定结果将不会传递if语句,因为!true = false

if(firstSchema.contains("test")) {
    System.out.println("Match found !");
}

if(!firstSchema.contains("test")) {
    System.out.println("Match not found !");
}

答案 3 :(得分:1)

如果想检查一个列表是否有匹配的元素,你可以这样做。

 List<String> firstSchema = new ArrayList<String>();
firstSchema.add(0,"test");
firstSchema.add(1,"testy");

List<String> testList = new ArrayList<String>(firstSchema);
testList.removeAll(firstSchema);

if(testList.size()<firstSchema.size()){
    System.out.println("some elements match");
}

您也可以类似地使用retainAll

答案 4 :(得分:1)

最简单的方法是使用Java 8流。

if(firstList.stream().anyMatch(secondList::contains))
    System.out.println("Content matched");

为了提高效率(如果您正在使用足够的数据使其真正重要)并且如果可能(唯一值),则secondList可以转换为HashSet