2

How to remove duplicate object from ArrayList, but only if one specific value from object repeats with another object?

For example: I have class named Person with fields:

private String city;
private String firstName;
private String lastName;
private Long magicNumber;

I want to remove "older" Person with same "magicNumber" as the new One and keep him in ArrayList.

tomasz pawlak
  • 151
  • 1
  • 7

3 Answers3

3

Using streams :

Collection<Person> filterd = persons.stream()
            .collect(Collectors.toMap(
                    Person::getMagicNumber, p -> p, (p1, p2) -> p2))
            .values();
Eritrean
  • 15,851
  • 3
  • 22
  • 28
0

Well, assuming you have overriden public boolean equals(Object object) in your class in order to compare your magicNumber field:

https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)

List<Person> persons = new ArrayList<>();
public void addToList(Person person) {
     if(persons.contains(person)) {
         persons.set(persons.indexOf(person), person);
     } else {
         persons.add(person);
     }

}
Huatxu
  • 111
  • 5
  • there is no `replace` method in `List`, you probably meant `set(int, Object)`. Also, you could remove the `contains`, calculate the index beforehand and then check if it is `< 0` in the condition. – Clashsoft Mar 04 '20 at 19:38
-1
public void addPerson(Person p) {
    list.removeIf(o -> o.magicNumber.equals(p.magicNumber));
    list.add(p);
}
Ryan
  • 1,762
  • 6
  • 11