有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何识别新嵌套列表与旧嵌套列表相比是否有任何添加或删除或相同的对象

我有两个列表,如下所示

List<Component> oldComps =getOldComps();
List<Component> newcomps=getNewComps();

相应的POJO包括:

public class Component {  
 private List<Endpoint> endpoints;
}

public class Endpoint {
private String path;    
}

我有一个用例需要识别:


  1. newComps和oldComps列表的数据是否相同
  2. 在newComps中添加/删除的组件中是否有oldcomps中没有的组件?如果有,请提供组件详细信息
  3. 是否在任何newComps列表组件中添加/删除了旧组件中没有的任何endponit?如果有,请提供详细信息

newComps

oldComps

详细示例:如所附图片所示,如果是oldcomp和newComps ==>;包含相同的数据


共 (2) 个答案

  1. # 1 楼答案

    假设你的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));
    
  2. # 2 楼答案

    您可以获得数据结构的哈希代码,这是许多现代编程语言上的内置函数,可以与另一种进行比较

    可以通过从所需的对象调用hashCode()方法来获得结果。在你的情况下,oldComps。hashCode()将给出结果

    更多信息:hashCode() by Baeldung