简单的问题.
我有一个新列表和一个旧列表.在Java中是否有标准的方法/库,允许我比较这两个列表并确定哪些项目已更新/删除或是全新的?例如,我应该最终得到三个列表 - 已删除的项目(旧的但不是新的项目),更新的项目(两者中的项目),新项目(新项目(不是旧项目).
我自己可以写这个,但想知道是否有标准的方法来做到这一点.
列表中的对象实现正确等于.
cle*_*tus 34
没有标准方式抱歉.您可以使用标准JDK轻松地完成它,而无需依赖于Apache Commons(正如其他人所建议的那样).假设您的列表是List<T>实例:
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);
Run Code Online (Sandbox Code Playgroud)
标准库中没有任何内容.
但是,Apache Commons CollectionUtils类为您提供了交叉和减法方法的功能:
Collection<T> old = ...;
Collection<T> neww = ...;
Collection<T> deleted = (Collection<T>)CollectionUtils.subtract(old, new);
Collection<T> updated = (Collection<T>)CollectionUtils.intersection(old, new);
Collection<T> newResult = (Collection<T>)CollectionUtils.subtract(new, old);
Run Code Online (Sandbox Code Playgroud)
(您需要(未经检查)强制转换,因为CollectionUtils未被广泛化.)