【问题标题】:Comparing Two Pojo List for changes比较两个 Pojo 列表的变化
【发布时间】:2021-10-05 10:25:40
【问题描述】:

我有两个 Pojo 课程 DriverPrimary, DriverSecondary

我正在比较主要驱动程序和次要驱动程序,如果有任何更改,我需要找出来

你能告诉我它是怎么做的吗?

DriverPrimary.java

public class DriverPrimary implements Serializable {

    private static final long serialVersionUID = 1L;

    private String DriverId;
    private String role;

    
}

DriverSecondary.java

public class DriverSecondary{

    private String driverSecondaryDriverType;
    private String driverSecondaryDriverId;

}
   List<DriverPrimary> driverPrimary = new ArrayList<DriverPrimary>();
   List<DriverSecondary> driverSecondary = new ArrayList<DriverSecondary>();

driverPrimary=DataEBO.getDriverPrimary();// from datasource which is not empty and has values
driverSecondary=DataDTO.getDriverSecondary();// from datasource which is not empty and has values

那么如何比较上面两个列表,虽然字段名称不同,但都有相似的值

编辑: 删除了 Equals 和 hashcode 可以与具有相同结构的类一起使用。 Edit2:修改了代码以便更好地理解

【问题讨论】:

  • 注意 java 命名约定。变量名应以小写字符开头
  • 更多细节会有所帮助,例如,driverPrimary 列表来自哪里,构造函数是什么样的。
  • @david 你想在这里检查什么?因为您检查给定的 secondary 驱动程序是否在 primary 驱动程序列表中。然而你说“改变了”和你给出的例子 - 这两个元素是不同的,所以不应该比较相等。
  • DriverPrimary 来自一个数据库 POJO,它被定义为一个列表,而 Driver Secondary 来自 Web 服务。所以我把它作为一个列表并能够获取值
  • 是的,我是 java 新手,所以只知道 equals 可以在相同的类结构上工作

标签: java list arraylist pojo


【解决方案1】:

其中一个列表应重新映射到另一种类型的类,以使列表的内容“可比较”:

// from datasource which is not empty and has values
List<DriverPrimary> primary = DataEBO.getDriverPrimary();
List<DriverPrimary> secondary = DataDTO.getDriverSecondary() // List<DriverSecondary>
        .stream()
        .map(sec -> new DriverPrimary(
            sec.getDriverSecondaryDriverId(),  // id  -> id
            sec.getDriverSecondaryDriverType() // type -> role
        ))
        .collect(Collectors.toList());  // List<DriverPrimary>

然后,假设equalshashCodeDriverPrimary 中正确实现,则可以使用例如List::removeAll(或仅List::equals)来发现这两个列表之间的差异。

List<DriverPrimary> diff1 = new ArrayList<>(primary);
diff1.removeAll(secondary); // items in primary missing in secondary

List<DriverPrimary> diff2 = new ArrayList<>(secondary);
diff2.removeAll(primary); // items in secondary missing in primary

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    相关资源
    最近更新 更多