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.

4

3 Answers 3

3

Using streams :

Collection<Person> filterd = persons.stream()
            .collect(Collectors.toMap(
                    Person::getMagicNumber, p -> p, (p1, p2) -> p2))
            .values();
Sign up to request clarification or add additional context in comments.

Comments

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);
     }

}

1 Comment

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.
-1
public void addPerson(Person p) {
    list.removeIf(o -> o.magicNumber.equals(p.magicNumber));
    list.add(p);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.