Member-only story

πŸš€ Java Streams: Bonus Hacks for Smarter Code!

Sanjay Singh
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!

πŸš€ Java Streams: Bonus Hacks for Smarter Code!

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

--

--

Sanjay Singh
Sanjay Singh

Written by Sanjay Singh

Java, Spring Boot & Microservices developer Sharing knowledge, tutorials & coding tips on my Medium page. Follow me for insights & see story list section

No responses yet