Wednesday, March 6, 2024

Java Stream - distinct() With Examples

In this tutorial you will see some examples of distinct() method in Java Stream API. Stream.distinct() method is used to remove duplicate elements and the method returns a new stream consisting of the distinct elements. To determine which elements are duplicates distinct() method uses the equals() method of the Object class.

distinct() in Java Stream

Syntax of the distinct() method is as given below-

Stream<T> distinct()

Here are some important points about the distinct operation.

  1. It is a stateful intermediate operation which means it may incorporate state from previously seen elements when processing new elements.
  2. Method takes no arguments and returns a new Stream consisting of the distinct elements.
  3. For ordered streams, distinct operation is stable i.e. if there are duplicate elements the element appearing first in the encounter order is preserved.
  4. For unordered streams there are no stability guarantees.

distinct method Java examples

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

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

public class StreamDistinct {
  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(1, 6, 1, 15, 4, 11, 15);
    numList.stream().distinct().forEach(System.out::println);
    
      List<String> nameList = Arrays.asList("Dan", "Preeti", "Dan", "Preeti", "Jean");
      List<String> distinctNameList = nameList.stream()
                             .distinct()
                             .collect(Collectors.toList());
      System.out.println(distinctNameList);
  }
}

Output

1
6
15
4
11
[Dan, Preeti, Jean]

2. Using distinct with custom objects. In the example objects of Employee class are used and we have to get distinct employees.

Employee class

public class Employee {
  private String empId;
  private int age;
  private String name;
  private char gender;
  private int salary;
  Employee(String empId, int age, String name, char gender, int salary){
    this.empId = empId;
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.salary = salary;
  }
  public String getEmpId() {
    return empId;
  }

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public char getGender() {
    return gender;
  }

  public int getSalary() {
    return salary;
  }
  @Override
  public String toString() {
      return "Emp Id: " +  getEmpId() + " Name: " + getName();
  }
  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((empId == null) ? 0 : empId.hashCode());
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    return result;
  }
  @Override
  // Equality based on id and name
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Employee other = (Employee) obj;
    if (empId == null) {
      if (other.empId != null)
        return false;
    } else if (!empId.equals(other.empId))
      return false;
    if (name == null) {
      if (other.name != null)
        return false;
    } else if (!name.equals(other.name))
      return false;
    return true;
  }
}
public class StreamDistinct {
  public static void main(String[] args) {
    List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                new Employee("E002", 35, "Shelly", 'F', 7000), 
                new Employee("E001", 40, "Ram", 'M', 5000), 
                new Employee("E004", 37, "Rani", 'F', 11000),
                new Employee("E002", 35, "Shelly", 'F', 7000), 
                new Employee("E006", 28, "Amy", 'F', 14000));  
    empList.stream().distinct().forEach(System.out::println);
  }
}

Output

Emp Id: E001 Name: Ram
Emp Id: E002 Name: Shelly
Emp Id: E004 Name: Rani
Emp Id: E006 Name: Amy

That's all for this topic Java Stream - distinct() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - filter() With Examples
  2. Java Stream - skip() With Examples
  3. Java Stream - count() With Examples
  4. Java Stream - Collectors.averagingInt(), averagingLong(), averagingDouble()
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. Volatile Keyword in Java With Examples
  2. Garbage Collection in Java
  3. Transient Keyword in Java With Examples
  4. Java BufferedWriter Class With Examples
  5. instanceof Operator in Java With Examples
  6. How to Display Time in AM-PM Format in Java
  7. Spring depends-on Attribute
  8. Spring Asynchronous Method Execution Support Using @Async Annotation

No comments:

Post a Comment