How to find unique elements from ArrayList by Java 8

Stream API provides distinct() method for finding unique elements. For this we need to provide implementation of hashcode() and equals() methods.


import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ArrayListDupRemoval {
public static void main(String[] args) {

Person p1 = new Person(1,"Gaurav","SS1");
Person p2 = new Person(2,"Gaurav","SS1");
Person p3 = new Person(3,"Gaurav","SS1");

List<Person> personList = new ArrayList<>();
personList.add(p1);
personList.add(p2);
personList.add(p3);

personList.stream()
.distinct()
.forEach(System.out::println);
}
}
class Person{

private int id;
private String name;
private String ssn;

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

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return
Objects.equals(ssn, person.ssn);
}

@Override
public int hashCode() {
return Objects.hash(ssn);
}

@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", ssn='" + ssn + '\'' +
'}';
}
}

Leave a Reply