Java 如何识别新嵌套列表与旧嵌套列表相比是否有任何添加或删除或相同的对象
我有两个列表,如下所示Java 如何识别新嵌套列表与旧嵌套列表相比是否有任何添加或删除或相同的对象,java,list,arraylist,Java,List,Arraylist,我有两个列表,如下所示 List<Component> oldComps =getOldComps(); List<Component> newcomps=getNewComps(); List oldComps=getOldComps(); List newcomps=getNewComps(); 相应的POJO为: public class Component { private List<Endpoint> endpoints; } publ
List<Component> oldComps =getOldComps();
List<Component> newcomps=getNewComps();
List oldComps=getOldComps();
List newcomps=getNewComps();
相应的POJO为:
public class Component {
private List<Endpoint> endpoints;
}
public class Endpoint {
private String path;
}
公共类组件{
私有列表端点;
}
公共类终结点{
私有字符串路径;
}
我有一个用例需要识别:
==>包含相同的数据。您可以获得数据结构的哈希代码,它是许多现代编程语言上的内置函数,可以与另一种语言进行比较 可以通过从所需的对象调用hashCode()方法来获得结果。在您的例子中,oldComps.hashCode()将给出结果
进一步说明:基于hashcode是否正确的假设
HashSet oldComponentSet = new HashSet(oldComps);
HashSet newComponentSet = new HashSet(newComps);
//this line will give you intersection
oldComponentSet.retainAll(setTwo);
// this line will give you difference
newComponentSet.removeAll(oldComponentSet)
//united differfence based on presumption above two lines were not executed
oldComponentSet.removeAll(newComponentSet).add(newComponentSet.removeAll(oldComponentSet));
您可以使用.equals()
方法来比较这两个列表
要查找不在其他列表中的任何组件,可以使用
list
类的.removeAll()
方法来标识唯一元素。给出相同数据的定义。我们谈论的是相同的对象-端点-“==”,还是平等意义上的相同数据?如果您可以为组件类实现equals和hashCode,然后使用Collections Utility或Guava collection为您的questions@FedericoPeraltaSchaffner我的坏:)太习惯函数语法了。我现在就修。