Skip to content
Advertisement

Merging instances of objects in a list by attribute

I have an object Person which has firstName, lastName and email

JavaScript

I have a list of Person where there are potentially multiple Persons of the same firstName and lastName and I want to merge these by their email address with a delimiter.

i.e. Person A =

JavaScript

Person B =

JavaScript

And I want these to be merged into

JavaScript

So as to create a unique instance in my list.

Advertisement

Answer

  1. It depends what you define as unique or equal. This could then be expressed by the equals and hashCode Method.

  2. you can use the java.util.stream.Collectors#toMap Method to provide a merge function and map your list to a map. In the merge function you can implement the logic how 2 objects with the same “key” should be handled.

    public class Person { public Person(String firstname, String lastName, String email) { this.firstname = firstname; this.lastName = lastName; this.email = email; }

    JavaScript

    }

If you don’t want to use equals and hashCode for this usecase you can of course just provide an own getKey Logic

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement