gpt4 book ai didi

java - 考虑某些字段检查 JAXB 对象的 equals

转载 作者:行者123 更新时间:2023-11-30 04:17:05 25 4
gpt4 key购买 nike

我自动生成的 JAXB 类

public class Employee {
private int id;
private String name;
private String department;

/* Getters and Setters */

}

Employee emp1 = new Employee();
emp1.setId(1);
emp1.setName("A");
emp1.setDepartment("D1");


Employee emp2 = new Employee();
emp2.setId(2);
emp2.setName("B");
emp2.setDepartment("D1");

List<Employee> empList1 = new ArrayList<Employee>();
empList1.add(emp1);
empList2.add(emp2);

Employee emp3 = new Employee();
emp2.setId(3);
emp2.setName("A");
emp2.setDepartment("D1");

List<Employee> empList2 = new ArrayList<Employee>();
empList2.add(emp3);

I want to compare both the list empList1 and empList2 and get a result list which matches name and department fields of Employee object.

基本上,我需要基于两个对象中字段的自定义比较来比较两个列表。

我正在查看 Google Guava 和 lambdaJ,但我无法找到通过自定义比较逻辑进行交集的解决方案/示例。

任何想法都会有帮助。

最佳答案

为了进行比较,您可以使用 Guava Ordering 或 Java Comparator。为了进行过滤,您可以使用谓词。

如果你想要一些通用的东西,你可以使用一个比较器(对于 DEP 和 NAME)

    class MyComparator implements Comparator<Employee> {

@Override
public int compare(final Employee left, final Employee right) {
return ComparisonChain.start().compare(left.getName(), right.getName())
.compare(left.getDepartment(), right.getDepartment()).result();
}

}

class MyPredicate implements Predicate<Employee> {

final List<Employee> employees;
final Comparator<Employee> comparator;

public MyPredicate(final List<Employee> employees, final Comparator<Employee> comparator) {
this.employees = employees;
this.comparator = comparator;
}

@Override
public boolean apply(@Nullable final Employee input) {
for (final Employee e : employees) {
if (comparator.compare(e, input) == 0) {
return true;
}

}

return false;
}

}

然后你可以像这样使用它:

    final MyComparator comparator = new MyComparator();
final MyPredicate predicate1 = new MyPredicate(empList1, comparator);
final MyPredicate predicate2 = new MyPredicate(empList2, comparator);
System.out.println("####");
System.out.println(Collections2.filter(empList2, predicate1));
System.out.println(Collections2.filter(empList1, predicate2));

关于java - 考虑某些字段检查 JAXB 对象的 equals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18107741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com