Вопрос

HashSet contains objects,I want to remove duplicates whose objects are having same id's

the following is the code..

Set<Employee> empSet=new HashSet<Employee>();
empSet.add(new Employee(1,"naresh"));
empSet.add(new Employee(2,"raj"));
empSet.add(new Employee(1,"nesh"));
empSet.add(new Employee(2,"rajes"));

//i saw in some blog that we can use hashCode equals method, but i don't how to use that in this context, please help me out

Это было полезно?

Решение

import groovy.transform.EqualsAndHashCode

@EqualsAndHashCode(includes='id')
class Employee {
    int id
    String name
}

You can remove constructors as well if @Canonical AST is used. Canonical also provides @EqualsAndHashCode, but to add the includes it has to be used separately again.

UPDATE

If the class is not modifiable and you have a list/hasSet then you can use unique with a closure to perform the uniqueness. Assuming the SolrDocument mentioned in comment is referred as Employee and you have the above HashSet with duplicate ids, then below should work:

empSet.unique { it.id } //this mutates the original list

empSet.unique( false ) { it.id } //this does not mutate the original  list

Другие советы

Write equals and hashCode as shown below

public class Employee {
    private int id;
    private String name;

    public Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Employee employee = (Employee) o;

        if (id != employee.id) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return id;
    }
}

You need to override equals() method in your Employee class and it will be taken care of. Set uses the equals method to compare the objects inserted in the Set.

public class Employee 
{
    public boolean equals(Employee e)
    {
       /// logic to compare 2 employee objects
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top