February 6, 2024

Java Stream distinct() With Examples

Java Stream distinct() method is used to get the distinct elements of the stream. It means this method filters out the duplicate elements.

Syntax of the distinct method

Syntax of the distinct() method in the Java Stream API is as given below-

Stream<T> distinct()

  1. Method returns a new stream consisting of the distinct elements.
  2. For element comparison distinct() method uses the equals() method.
  3. distinct() method is a stateful intermediate operation which means it may incorporate state from previously seen elements when processing new elements.
  4. If there are duplicate elements in an ordered stream the element appearing first in the encounter order is preserved. For unordered streams, no stability guarantees are made.

Java Stream distinct() examples

1. Using distinct() method to remove duplicate elements from a List of integers.

import java.util.List;

public class DistinctDemo {

  public static void main(String[] args) {
    // Till Java 8
    //List<Integer> myList = Arrays.asList(11, 1, 9, 1, 4, 11, 17);
    // From Java 9
    List<Integer> myList = List.of(11, 1, 9, 1, 4, 11, 17);
    myList.stream().distinct().forEach(System.out::println);
  }
}
Output
11
1
9
4
17

2. Same way from a List of strings also you can remove duplicates by using distinct() method.

import java.util.List;
import java.util.stream.Collectors;

public class DistinctDemo {

  public static void main(String[] args) {
    // Till Java 8
    //List<String> myList = Arrays.asList("Ram", "Madan", "Jack", "Ram", "Jack");
    // From Java 9
    List<String> myList = List.of("Ram", "Madan", "Jack", "Ram", "Jack");
    List<String> listWithNoDuplicates = myList.stream()
                           .distinct()
                           .collect(Collectors.toList());
    System.out.println(listWithNoDuplicates);
}
Output
[Ram, Madan, Jack]

3. Removing duplicates from a List of custom objects. Student class used is as given below.

public class Student {
  private int rollNo;
  private String name;
  private String stream;
  private int marks;
  Student(int rollNo, String name, String stream, int marks){
    this.rollNo = rollNo;
    this.name = name;
    this.stream = stream;
    this.marks = marks;
  }
  public int getRollNo() {
    return rollNo;
  }
  public void setRollNo(int rollNo) {
    this.rollNo = rollNo;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }

  public String getStream() {
    return stream;
  }
  public void setStream(String stream) {
    this.stream = stream;
  }
  public int getMarks() {
    return marks;
  }
  public void setMarks(int marks) {
    this.marks = marks;
  }
  @Override
  public String toString() {
    return "Roll Number: " +  getRollNo() + " Name: " + getName();
  }
  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    result = prime * result + rollNo;
    return result;
  }
  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Student other = (Student) obj;
    if (name == null) {
      if (other.name != null)
        return false;
    } else if (!name.equals(other.name))
      return false;
    if (rollNo != other.rollNo)
      return false;
    return true;
  }
}

As you can see hashCode() and equals() methods are also implemented as that is one of pre-requisite for the distinct() method to work correctly.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class DistinctDemo {

  public static void main(String[] args) {
    List<Student> studentList = Arrays.asList(new Student(1, "Peter", "Science", 75),
              new Student(2, "Ram", "Science", 99),
              new Student(3, "Priscilla", "Art", 68),
              new Student(2, "Ram", "Science", 99),
              new Student(1, "Peter", "Science", 75));
    List<Student> listWithNoDuplicates = studentList.stream()
                           .distinct()
                           .collect(Collectors.toList());
    System.out.println(listWithNoDuplicates);
}
Output
[Roll Number: 1 Name: Peter, Roll Number: 2 Name: Ram, Roll Number: 3 Name: Priscilla]

That's all for the topic Java Stream distinct() With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment