Member-only story
π Java Streams: Bonus Hacks for Smarter Code!
2 min readFeb 15, 2025
1οΈβ£ Filter Unique Elements with distinct()
Want to remove duplicates from your stream? distinct()
does the job effortlessly!
List<Integer> numbers = List.of(1, 2, 2, 3, 4, 4, 5);
List<Integer> uniqueNumbers = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(uniqueNumbers); // [1, 2, 3, 4, 5]
No more manual checks β just pure, clean data!
Story List Categories:
- About Me & List of Stories
- Java β All things Java-related.
- Java Interview Playbook: Your Go-To Reading List β For interview preparation.
- JAVA-8 β Dedicated to Java 8 topics.
- Spring Boot & Spring β Focused on Spring and Spring Boot.
- Microservices Topics List β Covering various microservices to
2οΈβ£ Limit Results Dynamically with limit(n)
Need only the first few results? limit(n)
ensures efficient data processing.
List<String> names = List.of("Alice", "Bob", "Charlie", "David", "Eve");
names.stream()
.limit(3)
.forEach(System.out::println);
// Output: Alice, Bob, Charlie