Java 比较两个列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2762093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Compare Two Lists
提问by user238384
I have two lists ( not java lists, you can say two columns)
我有两个列表(不是java列表,你可以说两列)
For example
例如
**List 1** **Lists 2**
milan hafil
dingo iga
iga dingo
elpha binga
hafil mike
meat dingo
milan
elpha
meat
iga
neeta.peeta
I'd like a method that returns how many elements are same. For this example it should be 3 and it should return me similar values of both list and different values too.
我想要一个返回多少元素相同的方法。对于这个例子,它应该是 3,它也应该返回列表和不同值的相似值。
Should I use hashmap if yes then what method to get my result?
如果是,我应该使用 hashmap 那么什么方法可以得到我的结果?
Please help
请帮忙
P.S: It is not a school assignment :) So if you just guide me it will be enough
PS:这不是学校作业 :) 所以如果你只是指导我就足够了
采纳答案by OscarRyz
EDIT
编辑
Here are two versions. One using ArrayList
and other using HashSet
这里有两个版本。一种使用ArrayList
和其他使用HashSet
Compare them and create your ownversion from this, until you get what you need.
比较它们并从中创建您自己的版本,直到您获得所需的内容。
This should be enough to cover the:
这应该足以涵盖:
P.S: It is not a school assignment :) So if you just guide me it will be enough
PS:这不是学校作业 :) 所以如果你只是指导我就足够了
part of your question.
你问题的一部分。
continuing with the original answer:
继续原来的答案:
You may use a java.util.Collection
and/or java.util.ArrayList
for that.
您可以使用 ajava.util.Collection
和/或 java.util.ArrayList
为此。
The retainAllmethod does the following:
该中的retainAll方法执行以下操作:
Retains only the elements in this collection that are contained in the specified collection
仅保留此集合中包含在指定集合中的元素
see this sample:
请参阅此示例:
import java.util.Collection;
import java.util.ArrayList;
import java.util.Arrays;
public class Repeated {
public static void main( String [] args ) {
Collection listOne = new ArrayList(Arrays.asList("milan","dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta"));
Collection listTwo = new ArrayList(Arrays.asList("hafil", "iga", "binga", "mike", "dingo"));
listOne.retainAll( listTwo );
System.out.println( listOne );
}
}
EDIT
编辑
For the second part ( similar values ) you may use the removeAllmethod:
对于第二部分(相似值),您可以使用removeAll方法:
Removes all of this collection's elements that are also contained in the specified collection.
移除也包含在指定集合中的所有此集合的元素。
This second version gives you also the similar values and handles repeated ( by discarding them).
第二个版本也为您提供了相似的值并重复处理(通过丢弃它们)。
This time the Collection
could be a Set
instead of a List
( the difference is, the Set doesn't allow repeated values )
这次Collection
可能是 aSet
而不是 a List
(区别在于 Set 不允许重复值)
import java.util.Collection;
import java.util.HashSet;
import java.util.Arrays;
class Repeated {
public static void main( String [] args ) {
Collection<String> listOne = Arrays.asList("milan","iga",
"dingo","iga",
"elpha","iga",
"hafil","iga",
"meat","iga",
"neeta.peeta","iga");
Collection<String> listTwo = Arrays.asList("hafil",
"iga",
"binga",
"mike",
"dingo","dingo","dingo");
Collection<String> similar = new HashSet<String>( listOne );
Collection<String> different = new HashSet<String>();
different.addAll( listOne );
different.addAll( listTwo );
similar.retainAll( listTwo );
different.removeAll( similar );
System.out.printf("One:%s%nTwo:%s%nSimilar:%s%nDifferent:%s%n", listOne, listTwo, similar, different);
}
}
Output:
输出:
$ java Repeated
One:[milan, iga, dingo, iga, elpha, iga, hafil, iga, meat, iga, neeta.peeta, iga]
Two:[hafil, iga, binga, mike, dingo, dingo, dingo]
Similar:[dingo, iga, hafil]
Different:[mike, binga, milan, meat, elpha, neeta.peeta]
If it doesn't do exactly what you need, it gives you a good start so you can handle from here.
如果它不能完全满足您的需求,它会给您一个良好的开端,这样您就可以从这里开始处理。
Question for the reader: How would you include all the repeated values?
读者问题:您将如何包含所有重复值?
回答by Stefan Kendall
Assuming hash1
and hash2
假设hash1
和hash2
List< String > sames = whatever
List< String > diffs = whatever
int count = 0;
for( String key : hash1.keySet() )
{
if( hash2.containsKey( key ) )
{
sames.add( key );
}
else
{
diffs.add( key );
}
}
//sames.size() contains the number of similar elements.
回答by polygenelubricants
Are these really lists(ordered, with duplicates), or are they sets(unordered, no duplicates)?
这些真的是列表(有序,有重复),还是集合(无序,没有重复)?
Because if it's the latter, then you can use, say, a java.util.HashSet<E>
and do this in expected linear time using the convenient retainAll
.
因为如果是后者,那么您可以使用,比如说, ajava.util.HashSet<E>
并使用方便的retainAll
.
List<String> list1 = Arrays.asList(
"milan", "milan", "iga", "dingo", "milan"
);
List<String> list2 = Arrays.asList(
"hafil", "milan", "dingo", "meat"
);
// intersection as set
Set<String> intersect = new HashSet<String>(list1);
intersect.retainAll(list2);
System.out.println(intersect.size()); // prints "2"
System.out.println(intersect); // prints "[milan, dingo]"
// intersection/union as list
List<String> intersectList = new ArrayList<String>();
intersectList.addAll(list1);
intersectList.addAll(list2);
intersectList.retainAll(intersect);
System.out.println(intersectList);
// prints "[milan, milan, dingo, milan, milan, dingo]"
// original lists are structurally unmodified
System.out.println(list1); // prints "[milan, milan, iga, dingo, milan]"
System.out.println(list2); // prints "[hafil, milan, dingo, meat]"
回答by Mihir Mathuria
You can try intersection()
and subtract()
methods from CollectionUtils
.
您可以尝试intersection()
,并subtract()
从方法CollectionUtils
。
intersection()
method gives you a collection containing common elements and the subtract()
method gives you all the uncommon ones.
intersection()
方法为您提供一个包含常见元素的集合,该subtract()
方法为您提供所有不常见的元素。
They should also take care of similar elements
他们也应该照顾类似的元素
回答by Manoj Kumar
I found a very basic example of List comparison at List CompareThis example verifies the size first and then checks the availability of the particular element of one list in another.
我在List Compare找到了一个非常基本的 List 比较 示例 这个示例首先验证大小,然后检查一个列表中特定元素在另一个列表中的可用性。
回答by Asanka Siriwardena
Using java 8 removeIf
使用 java 8 removeIf
public int getSimilarItems(){
List<String> one = Arrays.asList("milan", "dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta");
List<String> two = new ArrayList<>(Arrays.asList("hafil", "iga", "binga", "mike", "dingo")); //Cannot remove directly from array backed collection
int initial = two.size();
two.removeIf(one::contains);
return initial - two.size();
}
回答by Pavan Rangani
public static boolean compareList(List ls1, List ls2){
return ls1.containsAll(ls2) && ls1.size() == ls2.size() ? true :false;
}
public static void main(String[] args) {
ArrayList<String> one = new ArrayList<String>();
one.add("one");
one.add("two");
one.add("six");
ArrayList<String> two = new ArrayList<String>();
two.add("one");
two.add("six");
two.add("two");
System.out.println("Output1 :: " + compareList(one, two));
two.add("ten");
System.out.println("Output2 :: " + compareList(one, two));
}
回答by snowfox
If you are looking for a handy way to test the equality of two collections, you can use org.apache.commons.collections.CollectionUtils.isEqualCollection
, which compares two collections regardless of the ordering.
如果您正在寻找一种方便的方法来测试两个集合的相等性,您可以使用org.apache.commons.collections.CollectionUtils.isEqualCollection
,它会比较两个集合而不考虑排序。
回答by Opster Elasticsearch Pro-Vijay
Simple solution :-
简单的解决方案:-
List<String> list = new ArrayList<String>(Arrays.asList("a", "b", "d", "c"));
List<String> list2 = new ArrayList<String>(Arrays.asList("b", "f", "c"));
list.retainAll(list2);
list2.removeAll(list);
System.out.println("similiar " + list);
System.out.println("different " + list2);
Output :-
输出 :-
similiar [b, c]
different [f]
回答by shakhawat
Of all the approaches, I find using org.apache.commons.collections.CollectionUtils#isEqualCollection
is the best approach. Here are the reasons -
在所有方法中,我发现使用org.apache.commons.collections.CollectionUtils#isEqualCollection
是最好的方法。原因如下——
- I don't have to declare any additional list/set myself
- I am not mutating the input lists
- It's very efficient. It checks the equality in O(N) complexity.
- 我不必自己声明任何其他列表/设置
- 我没有改变输入列表
- 这是非常有效的。它检查 O(N) 复杂度的相等性。
If it's not possible to have apache.commons.collections
as a dependency, I would recommend to implement the algorithm it follows to check equality of the list because of it's efficiency.
如果不可能apache.commons.collections
作为依赖项,我会建议实施它遵循的算法来检查列表的相等性,因为它的效率。