Java 有效地比较两个ArrayList的内容
知道为什么Java 有效地比较两个ArrayList的内容,java,arraylist,collections,Java,Arraylist,Collections,知道为什么contains在这里不起作用吗,这些语句总是计算falsefirstSchema.contains(firstSchema.get(0)) List firstSchema=new ArrayList(); 添加(0,“测试”); 添加(1,“testy”); if(!(firstSchema.contains(firstSchema))){ System.out.println(“hey arraylist content matched”); } 如果一个arraylist中的
contains
在这里不起作用吗,这些语句总是计算falsefirstSchema.contains(firstSchema.get(0))
List firstSchema=new ArrayList();
添加(0,“测试”);
添加(1,“testy”);
if(!(firstSchema.contains(firstSchema))){
System.out.println(“hey arraylist content matched”);
}
如果一个arraylist中的任何一个或多个或所有元素与其他arraylist元素匹配,我需要得到true,因为您的检查不正确。请参阅
firstSchema.contains(firstSchema)
错误arrayList.contains(arrayList)
无效
其次(firstSchema.contains(“test”)
返回true
,就像数组列表包含test
和一样代码>否定结果将不会通过if
语句,因为!真=假
if(firstSchema.contains("test")) {
System.out.println("Match found !");
}
if(!firstSchema.contains("test")) {
System.out.println("Match not found !");
}
如果要检查一个列表是否有匹配的元素,可以执行以下操作
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");
}
List firstSchema=new ArrayList();
添加(0,“测试”);
添加(1,“testy”);
List testList=newarraylist(firstSchema);
removeAll(firstSchema);
if(testList.size()检查列表是否包含其他列表中的任何元素的最简单方法是调用其中一个列表,依次将每个元素作为参数传递。类似于:
public <E> boolean slowListContains(List<E> a, List<E> b) {
for (E element : a) {
if (b.contains(element)) {
return true;
}
}
return false;
}
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;
}
这并不完美,但肯定比简单的解决方案快得多。一个小小的改进是始终将较小的列表转换为集合,而不是第一个。您也可以使用任意可编辑的参数,而不是列表
参数,然后检查它们是否已经是取消设置,如果是,则跳过设置构造步骤。如果(!(firstSchema.contains(firstSchema)))
循环错误。您正在尝试在列表中查找与自身匹配的项。您无法检查列表是否包含自身。
下面是java文档中的contains是如何工作的
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 ? e==null : o.equals(e))</tt>.
如果此列表包含指定元素,则返回true。
更正式地说,当且仅当此列表包含
至少一个元素e使得
(o==null?e==null:o.equals(e))。
最简单的方法是使用Java8流
if(firstList.stream().anyMatch(secondList::contains))
System.out.println("Content matched");
为了提高效率(如果您使用的数据足够重要),如果可能(唯一值),可以将secondList
转换为HashSet
甚至firstSchema。包含(“测试”)
也不起作用:(@Swapnil:我觉得这很难相信。请发布一个演示-我猜你的实际测试程序还有其他事情在进行。(也不清楚你为什么要使用超负荷的add
,它需要索引。)@TAsk my bad,抱歉uu He It's Nice hack:)这是一个破坏性的操作,是O(n^2)运行时。这绝对不是一个好方法。提前终止并不意味着它是有效的,在一般情况下它仍然是二次运行时。@dimo414是的,我刚刚意识到给出的其他解决方案也没有那么糟糕。好吧,除了retainal
一个。非常感谢您的解释,先生:)
if(firstList.stream().anyMatch(secondList::contains))
System.out.println("Content matched");