Tuesday, February 20, 2018

How to remove duplicate using overriding equals and hashCode methods in Java

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class Person {
private String id;
private String name;

public String getId() {
return id;
}

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

public String getName() {
return name;
}

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

@Override
public String toString() {
return id + "-" + name;
}

@Override
public boolean equals(Object object) {
if (object == this) {
return true;
}

if (!(object instanceof Person)) {
return false;
}
final Person person = (Person) object;
return person.id.equals(id);
}

@Override
public int hashCode() {
int hash = 3;
hash = 53 * hash + (this.id != null ? this.id.hashCode() : 0);
return hash;
}

public static void main(String args[]) {
Set<Person> personSet = new HashSet<Person>();
List<Person> personList = new ArrayList<Person>();

Person person1 = new Person();
person1.setId("101");
person1.setName("Ravi");
personList.add(person1);

Person person2 = new Person();
person2.setId("101");
person2.setName("Raja");
personList.add(person2);

System.out.println("Original Elements:");
for (Iterator<Person> iterator = personList.iterator(); iterator
.hasNext();) {
System.out.println((Person) iterator.next());
}

personSet.addAll(personList);
System.out.println("Elements after removing duplicate id element:");
for (Iterator<Person> iterator = personSet.iterator(); iterator
.hasNext();) {
System.out.println((Person) iterator.next());
}
}
}

1 comment:

  1. Casino | Harrah's Cherokee Casino Hotel, NC - JamBase
    Experience over 1,000 slot and table games, the only 여수 출장샵 place to experience the excitement of 서산 출장샵 the Harrah's Cherokee Casino Resort. 안성 출장마사지 Make your gaming 군포 출장마사지 experience 순천 출장샵 real

    ReplyDelete

Create a REST API with Spring Boot

In this post, I will explain how to create a simple a REST API with Spring Boot Spring Boot Spring Boot is a framework that provides inbuil...