如何从基于键具有不同匹配的对象的两个ArrayList中取出属性

How to takeout attribute from two ArralyList of object which have different match based on key

如何从优化方式不同匹配的两个对象的ArralyList中取出属性。

我有两个对象数组列表,经过比较后,我根据属性取出具有差异的值。

所以在我的情况下,当列表中的 deptCOde 相同但 deptName 不同时,输出将更新 deptName。

这是我的代码。

public class educationMain {

    public static void main(String[] args) {
        
        List<person> list=new ArrayList<person>();  
        person l1 = new person(1,"Samual",100,"Sales","Business");
        person l2 = new person(2,"Alex",100,"Sales","Business");
        person l3 = new person(3,"Bob",101,"Engineering","Technology");
        person l4 = new person(4,"Michel",101,"Engineering","Technology");
        person l5 = new person(5,"Ryan",102,"PR","Services");
        person l6 = new person(6,"Horward",103,"Leadership","Managmnet");
        person l7 = new person(7,"Cyna",104,"HR","Human Resource");
        list.add(l1);  
        list.add(l2);  
        list.add(l3); 
        list.add(l4);  
        list.add(l5);  
        list.add(l6); 
        list.add(l7); 
        
        List<department> depList = new ArrayList<department>();
        
         department d1 = new department(100, "Sales","Business");
         department d2 = new department(101, "Engineering","Technology");
         department d3 = new department(102, "PR","Support");
         depList.add(d1);  
         depList.add(d2);  
         depList.add(d3); 

         List<person> listC = new ArrayList<person>();
         
         
         // My comparision Logic
         for(person p : list) {
             boolean  flag = false;
             for (department d:depList) {
                 if(p.deptCode == d.deptCode) {
                     if(p.deptName != d.deptName) {
                         p.deptName = d.deptName;
                         listC.add(p);
                     }
                 }
             }
         }
         
         for(person b:listC){  
             System.out.println(b.personId+" "+b.name+" "+b.deptCode+" "+b.parentDept+" "+b.deptName); 
         }
    }

}

这段代码运行良好,我正在获取输出。

5 Ryan 102 PR Support

但是除了使用两个 for 循环之外,我们是否有任何有效的方法来实现它。

您可以在单个循环中将 Department List 转换为 Map

Map<Integer, Department> map = depList.stream()
  .collect(Collectors.toMap(department -> department.deptCode, Function.identity()));

然后您可以在比较逻辑中使用单个循环,例如

 // My comparision Logic
     for(person p : list) {
         Department d = map.get(p.deptCode);
         if(!d.deptName.equals(p.deptName)) {
           p.deptName = d.deptName;
           listC.add(p);
         }
     }

少量优化:

  1. 根据部门代码对列表进行排序。(使用比较器 & Collections.sort)

  2. 写一个二进制搜索而不是两个 for 循环。

  3. 因为两个列表都已排序,所以继续搜索直到 (p.deptCode == d.deptCode) 等于 true 否则中断循环。