Java 如何返回两个列表之间的差异?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27002882/
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
How can I return the difference between two lists?
提问by Rory Lester
I have two array lists e.g.
我有两个数组列表,例如
List<Date> a;
contains : 10/10/2014, 10/11/2016
List<Date> b;
contains : 10/10/2016
How can i do a check between list a
and b
so the value that is missing in b
is returned?e.g. 10/10/2014
我如何在列表之间进行检查a
,b
以便b
返回缺少的值?例如10/10/2014
采纳答案by Pablo Santa Cruz
You can convert them to Set
collections, and perform a set difference operation on them.
您可以将它们转换为Set
集合,并对它们执行集差操作。
Like this:
像这样:
Set<Date> ad = new HashSet<Date>(a);
Set<Date> bd = new HashSet<Date>(b);
ad.removeAll(bd);
回答by Denis Lukenich
If you only want find missing values in b, you can do:
如果您只想在 b 中查找缺失值,您可以执行以下操作:
List toReturn = new ArrayList(a);
toReturn.removeAll(b);
return toReturn;
If you want to find out values which are present in either list you can execute upper code twice. With changed lists.
如果您想找出任一列表中存在的值,您可以执行两次上层代码。带有更改的列表。
回答by Jefferey Cave
I was looking for a different problem and came across this, so I will add my solution to a related problem: comparing two Maps.
我正在寻找一个不同的问题并遇到了这个问题,所以我将我的解决方案添加到一个相关的问题:比较两个地图。
// make a copy of the data
Map<String,String> a = new HashMap<String,String>(actual);
Map<String,String> e = new HashMap<String,String>(expected);
// check *every* expected value
for(Map.Entry<String, String> val : e.entrySet()){
// check for presence
if(!a.containsKey(val.getKey())){
System.out.println(String.format("Did not find expected value: %s", val.getKey()));
}
// check for equality
else{
if(0 != a.get(val.getKey()).compareTo(val.getValue())){
System.out.println(String.format("Value does not match expected: %s", val.getValue()));
}
// we have found the item, so remove it
// from future consideration. While it
// doesn't affect Java Maps, other types of sets
// may contain duplicates, this will flag those
// duplicates.
a.remove(val.getKey());
}
}
// check to see that we did not receive extra values
for(Map.Entry<String,String> val : a.entrySet()){
System.out.println(String.format("Found unexpected value: %s", val.getKey()));
}
It works on the same principle as the other solutions but also compares not only that values are present, but that they contain the same value. Mostly I've used this in accounting software when comparing data from two sources (Employee and Manager entered values match; Customer and Corporate transactions match; ... etc)
它的工作原理与其他解决方案相同,而且不仅比较存在的值,而且比较它们包含相同的值。大多数情况下,当比较来自两个来源的数据时,我在会计软件中使用了它(员工和经理输入的值匹配;客户和公司交易匹配;......等)
回答by contrapost
You can use CollectionUtils from Apache Commons Collections 4.0:
您可以使用Apache Commons Collections 4.0 中的 CollectionUtils:
new ArrayList<>(CollectionUtils.subtract(a, b))
回答by Milton Jacomini Neto
You can use filter by Java 8 Stream library
您可以通过 Java 8 Stream 库使用过滤器
List<String> aList = Arrays.asList("l","e","t","'","s");
List<String> bList = Arrays.asList("g","o","e","s","t");
List<String> result = aList.stream().filter(aObject -> {
return bList.contains(aObject);
}).collect(Collectors.toList());
//or more reduced without curly braces and return
List<String> result2 = aList.stream().filter(aObject ->
!bList.contains(aObject)).collect(Collectors.toList());
System.out.println(result);
Result:
结果:
[e, t, s]
回答by Valentyn Kolesnikov
You may call U.difference(lists)
method in underscore-javalibrary. I am the maintainer of the project. Live example
你可以调用U.difference(lists)
的方法下划线的Java库。我是项目的维护者。活生生的例子
import com.github.underscore.U;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(1, 2);
List<Integer> list3 = U.difference(list1, list2);
System.out.println(list3);
// [3]
}
}
回答by justMe
I was looking similar but I wanted the difference in either list (uncommon elements between the 2 lists):
我看起来很相似,但我想要两个列表中的差异(两个列表之间的不常见元素):
Let say I have:
假设我有:
List<String> oldKeys = Arrays.asList("key0","key1","key2","key5");
List<String> newKeys = Arrays.asList("key0","key2","key5", "key6");
And I wanted to know which key has been added and which key is removed i.e I wanted to get (key1, key6)
我想知道添加了哪个键,删除了哪个键,即我想获得(key1, key6)
Using org.apache.commons.collections.CollectionUtils
使用org.apache.commons.collections.CollectionUtils
List<String> list = new ArrayList<>(CollectionUtils.disjunction(newKeys, oldKeys));
Result
结果
[key1, key6]
[键1,键6]
回答by gs manisha
First convert list to sets.
首先将列表转换为集合。
// create an empty set
Set<T> set = new HashSet<>();
// Add each element of list into the set
for (T t : list)
set.add(t);
You can use Sets.difference(Set1, Set2)
, which returns extra items present in Set1.
You can use Sets.difference(Set2, Set1)
, which returns extra items present in Set2.
您可以使用Sets.difference(Set1, Set2)
,它返回 Set1 中存在的额外项目。
您可以使用Sets.difference(Set2, Set1)
,它返回 Set2 中存在的额外项目。
回答by madhu sairam gunnam
List<String> l1 = new ArrayList<String>();
l1.add("apple");
l1.add("orange");
l1.add("banana");
l1.add("strawberry");
List<String> l2 = new ArrayList<String>();
l2.add("apple");
l2.add("orange");
System.out.println(l1);
System.out.println(l2);
for (String A: l2) {
if (l1.contains(A))
l1.remove(A);
}
System.out.println("output");
System.out.println(l1);
Output:
输出:
[apple, orange, banana, strawberry]
[apple, orange]
output
[banana, strawberry]
回答by fuat
Here is a generic solution for this problem.
这是此问题的通用解决方案。
public <T> List<T> difference(List<T> first, List<T> second) {
List<T> toReturn = new ArrayList<>(first);
toReturn.removeAll(second);
return toReturn;
}