- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements