1

I have two list of Objects. I have framed this list by querying the database.

For Ex:

List<Employee> firstList={holDate,holName,createdby,empId}
List<Employee> seconList={holDate,holName,createdby,empId} 

Now, I need to compare holDate, holName of firstList with holDate, holName of secondList. If holDate, holName of firstList not found in secondList, I need to add that in separate list.

The list may be in any order.

NOTE: empId is a primary key column.

Update - what I've tried:

for(Employee emp:firstList) { 
    for(Employee tgtEmp:seconList) {  
        if((emp.getHolDate()!=tgtEmp.getHolDate())&& (emp.getHolName()!=tgtEmp.getHolName())){ 
            printList.add(emp); break; 
        } 
    }
}

Sample List Values:

firstList={{2015-08-15,"Independence Day","e1","Empl"},{2015-01-26,"Republic Day","e1","Empl"},{2015-09-20,"Memorial Day","e1","Empl"}}
seconList={{2015-08-15,"Independence Day","e1","Emp2"},{2015-10-25,"Thanks Giving Day","e1","Emp2"}}

Here, newlist should have all the values which is available in seconList and "RepublicDay","MemorialDay" from firstList

iShower
  • 79
  • 1
  • 6
  • 1
    What is `Employee`? Does it have a custom `equals` and `hashcode` method, cause it would really easy then to just use `List#removeAll` or `List#retainAll` to identify the duplicates. Of course, you could just both of them into some kind of `Set`... – MadProgrammer Jul 22 '15 at 07:24
  • 2
    You did any research before asking question? See plenty of question you can get in stackoverflow – Subodh Joshi Jul 22 '15 at 07:26
  • Hi Renjith, pls find below snippet
    for(Employee emp:firstList){ for(Employee tgtEmp:seconList){ if((emp.getHolDate()!=tgtEmp.getHolDate())&& (emp.getHolName()!=tgtEmp.getHolName())){ printList.add(emp); break; } } }
    – iShower Jul 22 '15 at 07:26
  • 2
    Why not do this at the db during extraction – Tuxxy_Thang Jul 22 '15 at 07:29

2 Answers2

1

Check this

 for (Employee emp : firstList) {
        boolean found=false;
        for (Employee tgtEmp : seconList) {
            if ((emp.getHolDate().equals(tgtEmp.getHolDate())) && (emp.getHolName().equals(tgtEmp.getHolName()))) {
                found=true;
                break;
            }
        }
        if(!found){
            printList.add(emp);
        }
    }
vels4j
  • 11,208
  • 5
  • 38
  • 63
0

I think the above answer is not generically. Think if you add any new field on the Emp object then you need to update the equals method. If you are open to accepting new solution then please consider the below answer

Assert List in Junit

Ganesa Vijayakumar
  • 2,422
  • 5
  • 28
  • 41