How to compare to Arraylist of object based on key in efficient way.
I have an array of object personDetails and departmentDetails.
Here I am trying to find the difference between the two object based on the attribute called deptCode.
Here is what I am trying.
package com.education;
import java.util.*;
import java.util.stream.Collectors;
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","Services");
depList.add(d1);
depList.add(d2);
depList.add(d3);
List<person> listC = new ArrayList<person>();
for(person p : list) {
boolean flag = false;
for (department d:depList) {
if(p.deptCode == d.deptCode) {
flag = false;
break;
}else {
flag = true;
}
}
if(flag == true) {
listC.add(p);
}
}
for(person b:listC){
System.out.println(b.personId+" "+b.name+" "+b.deptCode+" "+b.parentDept+" "+b.deptName);
}
}
}
Now this printing what eatly i want. But I am using two for loop. Can anyone help me to optimize my code because I am using two loop here. I want to try the code which filter out the delta based on some.
In Collection I saw set will do but not able to write that. Canone helpme to optimise the efiiciency.
Output :
6 Horward 103 Leadership Managmnet
7 Cyna 104 HR Human Resource