返回java中两个列表之间的差异
我有两个数组列表,例如
List a; contains : 10/10/2014, 10/11/2016 List b; contains : 10/10/2016
如何在列表a
和b
之间进行检查,以便返回b
缺少的值?例如10/10/2014
您可以将它们转换为Set
集合,并对它们执行set difference
操作。
喜欢这个:
Set ad = new HashSet (a); Set bd = new HashSet (b); ad.removeAll(bd);
如果您只想在b中找到缺失值,则可以执行以下操作:
List toReturn = new ArrayList(a); toReturn.removeAll(b); return toReturn;
如果要查找列表中存在的值,可以执行两次上码。 随着更改列表。
您可以使用Apache Commons Collections 4.0中的CollectionUtils :
new ArrayList<>(CollectionUtils.subtract(a, b))
我正在寻找一个不同的问题,并遇到了这个,所以我将我的解决方案添加到一个相关的问题:比较两个地图。
// make a copy of the data Map a = new HashMap(actual); Map e = new HashMap(expected); // check *every* expected value for(Map.Entry 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 val : a.entrySet()){ System.out.println(String.format("Found unexpected value: %s", val.getKey())); }
它的工作原理与其他解决方案相同,但不仅要比较存在的值,还要包含相同的值。 大多数情况下,我在会计软件中使用它来比较来自两个来源的数据(员工和经理输入的值匹配;客户和公司交易匹配;等等)
您可以使用Java 8 Stream库过滤
List aList = Arrays.asList("l","e","t","'","s"); List bList = Arrays.asList("g","o","e","s","t"); List result = aList.stream().filter(aObject -> { return bList.contains(aObject); }).collect(Collectors.toList()); //or more reduced without curly braces and return List result2 = aList.stream().filter(aObject -> bList.contains(aObject)).collect(Collectors.toList()); System.out.println(result);
结果:
[e, t, s]
您可以在underscore-java库中调用U.difference(lists)方法。 我是该项目的维护者。 实例
import com.github.underscore.U; import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List list1 = Arrays.asList(1, 2, 3); List list2 = Arrays.asList(1, 2); List list3 = U.difference(list1, list2); System.out.println(list3); // [3] } }