比较两个列表的更新,删除和添加 [英] Compare two lists for updates, deletions and additions

查看:417
本文介绍了比较两个列表的更新,删除和添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的问题。



我有一个新的列表和一个旧的列表。在Java中有一个标准的方式/库,允许我比较这两个列表,确定哪些项目已更新/删除或完全是新的?例如。我最终会得到三个列表 - 已删除的项目(旧项目,但不是新项目),已更新项目(两者中的项目),新项目(新项目而不是旧项目)。

我可以自己写,但是想知道是否有一个标准的方法来做。



列表中的对象正确实现了equals。

解决方案

没有标准的方法对不起。你可以很容易地与标准的JDK做,而不诉诸增加一个依赖Apache Commons(像其他人建议的)。假设您的列表为 List< T> 实例:

 列表< T& oldList = ... 
List< T> newList = ...

List< T> remove = new ArrayList< T>(oldList);
removed.removeAll(newList);

List< T> same = new ArrayList< T>(oldList);
same.retainAll(newList);

List< T> added = new ArrayList< T>(newList);
added.removeAll(oldList);


Simple question.

I have a new list and an old list. In Java is there a standard way/library that allows me to compare these two lists and determine which items have been updated/deleted or are completely new? E.g. I should end up with three lists - Deleted items (items in old but not in new), Updated items (items in both), New items (items in new and not in old).

I could write this myself but was wondering if there is a standard way to do it.

The objects in the list implement equals correctly.

解决方案

No standard way sorry. You can do it fairly easily with the standard JDK without resorting to adding a dependency on Apache Commons (as others have suggested) however. Assuming your lists are List<T> instances:

List<T> oldList = ...
List<T> newList= ...

List<T> removed = new ArrayList<T>(oldList);
removed.removeAll(newList);

List<T> same = new ArrayList<T>(oldList);
same.retainAll(newList);

List<T> added = new ArrayList<T>(newList);
added.removeAll(oldList);

这篇关于比较两个列表的更新,删除和添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆