Stream.distinct() in Java


The distinct() method of the stream class returns a stream consisting of the distinct elements of this stream. The syntax is as following −

Stream<T> distinct()

Example

Following is an example to implement the distinct() method in the Stream class −

import java.util.*;
public class Demo {
   public static void main(String[] args) {
      List<Integer> list = Arrays.asList(10, 30, 40, 40, 50, 70, 90, 90, 100);
      System.out.println("List = "+list);
      System.out.println("Displaying only the distinct elements = ");
      list.stream().distinct().forEach(System.out::println);
   }
}

Output

List = [10, 30, 40, 40, 50, 70, 90, 90, 100]
Displaying only the distinct elements =
10
30
40
50
70
90
100

Example

Let us see another example −

import java.util.*;
public class Demo {
   public static void main(String[] args) {
      List<Integer> list = Arrays.asList(10, 30, 40, 40, 50, 70, 90, 90, 100);
      System.out.println("List = "+list);
      System.out.println("Count of distinct elements = "+(list.stream().distinct().count()));
      System.out.println("Displaying only the distinct elements = ");
      list.stream().distinct().forEach(System.out::println);
   }
}

Output

List = [10, 30, 40, 40, 50, 70, 90, 90, 100]
Count of distinct elements = 7
Displaying only the distinct elements =
10
30
40
50
70
90
100

Updated on: 25-Sep-2019

441 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements