Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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 −
Streamdistinct()
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 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 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
Advertisements
