0

I have a database table with Person objects. My web service receives a list of Person objects to update this Person table. My application now contains 2 lists:

List<Person> current;
List<Person> updated;

I want to iterate through these lists and create a new list that I will use to update the Person table.

Person {
   String fName;
   String lName;
   String age;       
   String email;
}

fName and lName are used to identify existing records. The following is an example.

Current

Joe, Bloggs, 18, joe@me.com
Jane, Bloggs, 21, jane@me.com
Flo, Bloggs, 25, flo@me.com

New

Joe, Bloggs, 18, joe_bloggs@me.com
Jane, Bloggs, 21, jane@me.com
Flo, Bloggs, 90, flo@me.com

Records to update database with

Joe, Bloggs, 18, joe_bloggs@me.com
Flo, Bloggs, 90, flo@me.com

    private newList(List<Person> current, List<Person> new) {
      List<Person> toUpdate = new ArrayList();
      for(Person person : new) {
         Person found = current.stream().filter(p->p.equals(person)).findFirst().orElse(person);
      if (found.age!=person.age OR found.email!=person.email) {
         toUpdate.add(person);
      }
      return toUpdate;
    }
TheCoder
  • 8,413
  • 15
  • 42
  • 54

1 Answers1

0

Unless you override equals method in your Person class to actually check for the fields, you need to check the values of the object and not the references. Here is an example that will work assuming, lname and fname are used to identify a record. Also, as for the records that are the same, we don't have to add them to the list so our filter method will return an empty object, to deal with that we can use Optional.

A more efficient way would be to create a HashMap with fname and lname as keys and person object as value, then you won't have to filter again and again, thus, reducing running time by a factor of n.

   private newList(List<Person> old, List<Person> updated) {
      List<Person> toUpdate = new ArrayList<Person>();
      for(Person person : old) {
          
         Optional<Person> found = 
                  updated
                  .stream()
                  .filter(p-> p.fname == person.fname 
                          && p.lname == person.lname && 
                             (p.email != person.email 
                          || p.age != person.age)).findFirst();
         
         if(found.isPresent()) {
             Person f = found.get();
             toUpdate.add(f);
         }
     }
         return toUpdate;
         
  }
Lakshya
  • 684
  • 6
  • 10