📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
Java Streams, introduced in Java 8, bring a functional programming flavor to Java by allowing you to process collections of data in a declarative and concise manner. A stream represents a sequence of elements supporting sequential and parallel operations.
Unlike collections, a stream does not store data. Instead, it conveys elements from a source such as a collection, an array, or an I/O channel through a pipeline of computational operations.
Think of streams as data pipelines where each element flows through a series of transformations (intermediate operations) and ends in a result (terminal operation).
Check out a complete Java Streams course on Medium:
This is the Ultimate Guide to learn everything about Java Stream API with examples, real-world use cases and best…rameshfadatare.medium.com
Key Characteristics of Java Streams
- Declarative: Describe what you want to do, not how.
- Lazy Evaluation: Intermediate operations are only executed when a terminal operation is triggered.
- No Side Effects: Stream operations should not mutate the underlying source.
In this article, we cover every method available in the java.util.stream.Stream
interface, categorized by:
- Creation Methods
- Intermediate Operations
- Terminal Operations
- Utility Methods
🔄 Stream Creation Methods
1. Stream.of(...)
Creates a stream from values.
Stream<String> stream = Stream.of("Java", "Python", "Kotlin");
2. Stream.empty()
Returns an empty stream.
Stream<String> empty = Stream.empty();
3. Stream.generate(Supplier)
Generates an infinite stream using a Supplier
.
Stream<Double> randoms = Stream.generate(Math::random).limit(5);
4. Stream.iterate(...)
Generates an infinite stream by iterative function.
Stream<Integer> evens = Stream.iterate(0, n -> n + 2).limit(5);
5. Collection.stream()
Creates a stream from a collection.
List<String> list = List.of("A", "B", "C");
Stream<String> stream = list.stream();
🧹 Intermediate Operations (Lazy)
These return a new stream and are lazy (executed only when a terminal operation is triggered).
6. filter(Predicate)
Filters elements based on a condition.
list.stream().filter(s -> s.startsWith("A"))
7. map(Function)
Transforms elements.
list.stream().map(String::toUpperCase)
8. flatMap(Function)
Flattens nested streams.
Stream<List<String>> listOfLists = ...;
listOfLists.flatMap(List::stream)
9. distinct()
Removes duplicate elements.
list.stream().distinct()
10. sorted()
Sorts elements naturally.
list.stream().sorted()
11. sorted(Comparator)
Sorts elements using a custom comparator.
list.stream().sorted(Comparator.reverseOrder())
12. peek(Consumer)
Allows debugging by peeking each element.
list.stream().peek(System.out::println)
13. limit(long n)
Limits the number of elements.
list.stream().limit(3)
14. skip(long n)
Skips the first n elements.
list.stream().skip(2)
15. takeWhile(Predicate)
(Java 9+)
Takes elements while the condition is true.
list.stream().takeWhile(s -> s.length() < 5)
16. dropWhile(Predicate)
(Java 9+)
Skips elements while condition is true.
list.stream().dropWhile(s -> s.length() < 5)
🚦 Terminal Operations (Eager)
These trigger the execution of the stream pipeline.
17. forEach(Consumer)
Performs an action on each element.
list.stream().forEach(System.out::println);
18. forEachOrdered(Consumer)
Processes elements in encounter order.
list.parallelStream().forEachOrdered(System.out::println);
19. toArray()
Converts stream to an array.
String[] array = list.stream().toArray(String[]::new);
20. reduce(...)
Reduces the elements into one using an accumulator.
int sum = list.stream().reduce(0, Integer::sum);
21. collect(Collector)
Collects elements into a collection or summary.
List<String> collected = list.stream().collect(Collectors.toList());
22. min(Comparator)
Finds the minimum element.
Optional<String> min = list.stream().min(Comparator.naturalOrder());
23. max(Comparator)
Finds the maximum element.
Optional<String> max = list.stream().max(Comparator.naturalOrder());
24. count()
Counts the number of elements.
long count = list.stream().count();
25. anyMatch(Predicate)
Returns true if any element matches.
boolean hasA = list.stream().anyMatch(s -> s.startsWith("A"));
26. allMatch(Predicate)
Returns true if all elements match.
boolean allShort = list.stream().allMatch(s -> s.length() < 10);
27. noneMatch(Predicate)
Returns true if no elements match.
boolean noneEmpty = list.stream().noneMatch(String::isEmpty);
28. findFirst()
Returns the first element.
Optional<String> first = list.stream().findFirst();
29. findAny()
Returns any element (useful in parallel streams).
Optional<String> any = list.stream().findAny();
🛠️ Utility Methods
30. builder()
Used to build a stream manually.
Stream<String> stream = Stream.<String>builder().add("A").add("B").build();
31. concat(Stream, Stream)
Concatenates two streams.
Stream<String> combined = Stream.concat(stream1, stream2);
32. ofNullable(T)
(Java 9+)
Creates a stream of one element or empty if null.
Stream<String> maybe = Stream.ofNullable(possibleNull);
Final Thoughts
Java Streams simplify collection processing by enabling fluent, functional-style operations. Mastering each method helps you write concise, powerful, and readable code.
Use this article as your go-to reference when working with Java Streams!
References
This is the Ultimate Guide to learn everything about Java Stream API with examples, real-world use cases and best…rameshfadatare.medium.com
Java Stream Collectors are one of the most powerful features in the Stream API. They help you gather, group, join, or…medium.com
I Recommend this Related Udemy Course
Check out my best Udemy Course: Functional Programming in Java (Includes Java Collections)
In this course you will learn Java Lambda Expressions, Functional Interfaces, Stream API, and Collections Framework. Write Clean & Concise Code.
Comments
Post a Comment
Leave Comment