Mastering Java Streams: The Power of the distinct() Method

Java, a versatile and widely-used programming language, offers a plethora of features and tools to make coding efficient and streamlined. Among these tools, Java Streams stand out for their ability to process sequences of elements (e.g., collections) in a functional style. One of the lesser-known yet powerful methods within the Stream API is the distinct() method. In this article, we delve deep into the distinct() method, showcasing its capabilities and practical applications.

graph TD A[Input Stream: 2,3,4,3,2,3,4,1,2,4,5,1] B["distinct()"] C[Output Stream: 2,3,4,1,5] A --> B B --> C

Understanding the Role of distinct()

Java Streams are designed to handle sequences of elements, allowing developers to perform operations like filtering, mapping, and collecting. While many are familiar with methods like map, filter, and collect, the distinct() method often goes unnoticed.

The primary role of the distinct() method is to filter out duplicate elements from a Stream. It achieves this by leveraging the hashCode() and equals() methods, which are instrumental in comparing objects.

Java
List<Integer> numbers = Arrays.asList(2, 3, 4, 3, 2, 3, 4, 1, 2, 4, 5, 1);
numbers.stream().distinct().forEach(System.out::println);

Executing the above code would yield the output:

Java
2
3
4
1
5

The distinct() method returns a new Stream with unique values, allowing further operations to be performed on this filtered Stream.

Enhancing distinct() with Sorting

For those who desire not only unique values but also a sorted list, Java Streams offer a solution. By chaining the sorted() method after distinct(), one can obtain a Stream of unique, sorted values.

Java
numbers.stream().distinct().sorted().forEach(System.out::println);

This would produce:

Java
1
2
3
4
5

Counting Unique Elements

Another practical use of the distinct() method is to determine the number of unique elements in a collection. This can be achieved by chaining the count() method.

Java
long uniqueCount = numbers.stream().distinct().count();
System.out.println("Number of unique elements: " + uniqueCount);

The output would be:

Java
Number of unique elements: 5

Conclusion

Java Streams, with their vast array of methods, empower developers to write concise and efficient code. The distinct() method, in particular, is a gem that aids in filtering out duplicates, ensuring data integrity. By understanding and leveraging this method, developers can further enhance their Java coding skills and produce cleaner, more efficient code.

Author