3

In the below code I have added 5 objects with same data in hashset and I want to eliminate the object with duplicate data and print the object data which are distinct.

public static void main(String[] args) {
Employee emp1 = new Employee(1,"sandhiya","cse",22);
Employee emp2 = new Employee(1,"sandhiya","cse",22);
Employee emp3 = new Employee(1,"sandhiya","cse",22);
Employee emp4 = new Employee(1,"sandhiya","cse",22);
Employee emp5 = new Employee(1,"sandhiya","cse",22);
HashSet<Employee> emps = new HashSet<Employee>();
emps.add(emp1);
emps.add(emp2);
emps.add(emp3);
emps.add(emp4);
emps.add(emp5);
for(Employee e: emps){
    System.out.println(e.id + " "+e.name+" "+e.department+ " "+e.age);
}


}
shasha
  • 97
  • 1
  • 1
  • 7
  • 2
    A HashSet can handle it automatically. What you need to do is override `hashCode` and `equal` method in Employee, which will tell HashSet how to determine two objects are equal. https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java Here is an example. http://tutorials.jenkov.com/java-collections/hashcode-equals.html – xingbin Oct 04 '18 at 13:20
  • 1
    Your element class has to implement consistent `.equals()` and `.hashCode()` operations. – Pointy Oct 04 '18 at 13:20
  • 4
    By definition HashSet will contain only unique elements. The problem here is that the Employee class doesn't override HashCode and Equals methods of the Object class. – dbl Oct 04 '18 at 13:20

4 Answers4

6

HashSet uses a hash to compare objects.

You have to define equals and hashCode for your Employee class.

dehasi
  • 2,644
  • 1
  • 19
  • 31
2

You need to implement the hashcode() and equals() method in your Employee class.

reebow
  • 525
  • 1
  • 4
  • 15
1

As long as this is not getting duplicated the correct answer is:

If you don't want duplicates in a Collection, you should consider why you're using a Collection that allows duplicates. The easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList:

List<String> al = new ArrayList<>();
// add elements to al, including duplicates
Set<String> hs = new HashSet<>();
hs.addAll(al);
al.clear();
al.addAll(hs);

Of course, this destroys the ordering of the elements in the ArrayList.

See also LinkedHashSet, if you wish to retain the order.

Credits to: jonathan-stafford - the answer here

Sir. Hedgehog
  • 1,260
  • 3
  • 17
  • 40
0

Your equals method needs to be set. A hash set should not allow for two "equal" objects to exist.

Create an equals method for Employee.

CoupFlu
  • 311
  • 4
  • 20