[Go to site: main page, start]

0% found this document useful (0 votes)
45 views13 pages

Mastering Java Stream Operations

The document provides an overview of Java Streams, introduced in Java 8, highlighting their ability to simplify data processing through functional programming techniques. It details stream creation methods, intermediate and terminal operations, and the use of collectors, along with practical examples and practice questions. Additionally, it compares sequential and parallel streams, emphasizing their appropriate use cases and performance considerations.

Uploaded by

Shivam Kr Gupta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views13 pages

Mastering Java Stream Operations

The document provides an overview of Java Streams, introduced in Java 8, highlighting their ability to simplify data processing through functional programming techniques. It details stream creation methods, intermediate and terminal operations, and the use of collectors, along with practical examples and practice questions. Additionally, it compares sequential and parallel streams, emphasizing their appropriate use cases and performance considerations.

Uploaded by

Shivam Kr Gupta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

🔹 Java Streams: Where Simplicity Meets Power

Think you know Java? Streams will challenge that.

With just a few lines of code, Java Streams can replace complex loops, unlock
parallelism, and turn data processing into elegant expressions. It’s not just
about shorter code — it’s about thinking differently.

Get ready to write logic that’s clean, fast, and functional. From chaining
operations to embracing immutability and lazy evaluation, Streams reward
those who master their flow — and punish those who don’t.

Simple in syntax. Brutal in depth.


Welcome to the thinking developer’s API.

#[Link] @codetechtone [Link] [Link]/in/pkprusty999


📜 Java Stream Methods
Streams are introduced in Java 8. They allow processing of collections in a functional style
chaining multiple operations together.

 Streams don't store data; they process data.


 Streams are consumed once — you cannot reuse a stream after a terminal operation.
 Stream operations can be chained.
 Prefer parallel streams only when it can truly improve performance (large data + non-thread blocking
code).

Main Interfaces:
 Stream<T>
 IntStream, LongStream, DoubleStream

1. Creation of Streams
Method Description Example
stream() Converts a collection into a sequential [Link]()

stream

parallelStream() Converts collection into a parallel stream [Link]()

[Link](...) Creates stream from values [Link](1, 2, 3)

[Link](array) Creates stream from an array [Link](new int[]{1,2,3})

#[Link] @codetechtone [Link] [Link]/in/pkprusty999


2. Intermediate Operations (returns a new Stream, lazy evaluation)

Method Description Example


filter(Predicate) Select elements matching a [Link](x -> x > 5)

condition
map(Function) Transform elements [Link](String::toUpperCase)

flatMap(Function) Flattens nested structures [Link](list -> [Link]())

distinct() Removes duplicates (based on [Link]()

equals())
sorted() Sorts elements (natural order) [Link]()

sorted(Comparator) Custom sorting [Link]([Link]())

limit(n) Limits stream to n elements [Link](5)

skip(n) Skips first n elements [Link](3)

peek(Consumer) Perform action without consuming [Link]([Link]::println)

Note: Intermediate operations are lazy — no processing happens until a terminal operation
is called.

#[Link] @codetechtone [Link] [Link]/in/pkprusty999


3. Terminal Operations (triggers stream processing)
Method Description Example
collect(Collector) Collects elements into a [Link]([Link]())

collection
forEach(Consumer) Performs an action for each [Link]([Link]::println)

element
toArray() Converts stream into array [Link]()

reduce(BinaryOperator) Combines elements into a [Link](0, Integer::sum)

single result
count() Counts number of elements [Link]()

min(Comparator) Smallest element based on [Link]([Link]())

comparator
max(Comparator) Largest element based on [Link]([Link]())

comparator
anyMatch(Predicate) True if any element [Link](x -> x > 10)

matches
allMatch(Predicate) True if all elements match [Link](x -> x > 0)

noneMatch(Predicate) True if no element matches [Link](x -> x < 0)

findFirst() Returns first element [Link]()

(Optional)
findAny() Returns any element (useful [Link]()

in parallel)

#[Link] @codetechtone [Link] [Link]/in/pkprusty999


4. Collectors (for collect())
 [Link]() → Collects into a List
 [Link]() → Collects into a Set
 [Link](keyMapper, valueMapper) → Collects into a Map
 [Link](Function) → Groups elements by a key
 [Link](Predicate) → Partitions elements into two groups
(true/false)
List<String> names = [Link]("Alice", "Bob", "Charlie");
Map<Integer, List<String>> groupedByLength = [Link]()
.collect([Link](String::length));

5. Special Stream Types


IntStream, LongStream, Streams for primitives (no [Link](1,5)
DoubleStream boxing)

Methods like sum(), average(), min(), max() are available directly on primitive streams.

#[Link] @codetechtone [Link] [Link]/in/pkprusty999


🆚 Difference Between stream() and parallelStream()
Feature stream() parallelStream()
Processing Sequential: one element at a Parallel: splits data into multiple chunks and
time, in one thread (usually main processes them simultaneously using multiple
thread). threads (ForkJoinPool).

Speed Good for small or simple Can be faster for large datasets if system has
datasets. multiple cores.

Threading Sin6gle thread. Multiple threads.


Order Preserves the original order of Order is not guaranteed unless forced (e.g.,
elements. forEachOrdered).

Performance Simple and low overhead. Adds overhead due to splitting and combining —
benefits only when heavy work is done.

Usage Example [Link]().filter(x -> x > [Link]().filter(x -> x > 5).collect(...)


5).collect(...)

Ideal Use Case Small datasets, operations where Large datasets, CPU-intensive operations, when
order matters, I/O operations. order doesn't matter much.

Underlying Iterates items one by one. Uses [Link] internally to divide


Mechanism tasks.

#[Link] @codetechtone [Link] [Link]/in/pkprusty999


📋 Java Stream Practice Questions (with Solutions)

Q1: Given a list of integers, return a list of only even numbers.


List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6);

Sol List<List<Integer>> pairs = [Link]()


.flatMap(i -> [Link]()
.filter(j -> i < j && i + j == target)
.map(j -> [Link](i, j)))
.collect([Link]());

[Link](pairs); // Output: [[2, 8], [3, 7], [4, 6]]

Q2: From a list, find all pairs that sum to a given number (e.g., 10).
List<Integer> nums = [Link](1, 2, 3, 7, 5, 8, 6, 4);
int target = 10;

Sol List<String> upperNames = [Link]()


.map(String::toUpperCase)
.collect([Link]());

[Link](upperNames); // Output: [ALICE, BOB, CHARLIE]

Q3: Find the first string that starts with letter "C".
List<String> names = [Link]("Alice", "Bob", "Charlie", "David");

Sol Optional<String> firstNameStartingWithC = [Link]()


.filter(name -> [Link]("C"))
.findFirst();

[Link]([Link]::println); // Output:
Charlie

#[Link] @codetechtone [Link] [Link]/in/pkprusty999


Q4: Find the sum of squares of numbers in a list.
List<Integer> numbers = [Link](1, 2, 3, 4);
Sol
int sumOfSquares = [Link]()
.map(n -> n * n)
.reduce(0, Integer::sum);

[Link](sumOfSquares); // Output: 30 (1+4+9+16)

Q5: Sort a list of strings in descending (reverse alphabetical) order.


List<String> fruits = [Link]("apple", "banana", "cherry", "date");
Sol
List<String> sortedFruits = [Link]()
.sorted([Link]())
.collect([Link]());

[Link](sortedFruits); // Output: [date, cherry, banana, apple]

Q6: Group words by their length.


List<String> words = [Link]("one", "two", "three", "four", "five");

Sol Map<Integer, List<String>> groupedByLength = [Link]()


.collect([Link](String::length));

[Link](groupedByLength);
// Output: {3=[one, two], 5=[three], 4=[four, five]}

Q7: Find the maximum number in a list.


List<Integer> numbers = [Link](10, 20, 5, 80, 30);

Sol Optional<Integer> maxNumber = [Link]()


.max(Integer::compare);
[Link]([Link]::println); // Output: 80

#[Link] @codetechtone [Link] [Link]/in/pkprusty999


Q8: Count how many strings start with "A".
List<String> names = [Link]("Alice", "Arnold", "Bob", "Charlie",
"Andrew");

Sol long count = [Link]()


.filter(name -> [Link]("A"))
.count();

[Link](count); // Output: 3

Q9: Given a list of strings, group them by anagram sets.


List<String> words = [Link]("listen", "silent", "enlist", "rat",
"tar", "art");

Sol Map<String, List<String>> anagramGroups = [Link]()


.collect([Link](
word -> [Link]()
.sorted()
.mapToObj(c -> [Link]((char)c))
.collect([Link]())
));

// Output: {eilnst=[listen, silent, enlist], art=[rat, tar, art]}

Q10: Convert a list of lists into a single list.


List<List<String>> nestedList = [Link](
[Link]("a", "b"),
[Link]("c", "d"),
[Link]("e", "f")
);
Sol List<String> flatList = [Link]()
.flatMap(Collection::stream)
.collect([Link]());

[Link](flatList); // Output: [a, b, c, d, e, f]

#[Link] @codetechtone [Link] [Link]/in/pkprusty999


Q11: Given a list of integers, return a list of strings "even" or "odd" depending on
whether the number is even or odd.
List<Integer> numbers = [Link](1, 2, 3, 4, 5);

Sol List<String> evenOrOdd = [Link]()


.map(n -> n % 2 == 0 ? "even" : "odd")
.collect([Link]());

[Link](evenOrOdd); // Output: [odd, even, odd, even, odd]

Q12: Given a list of sentences, count the frequency of each word (case-insensitive).
List<String> sentences = [Link]("Java is fun", "Streams are
powerful", "Java is powerful");

Sol Map<String, Long> wordFreq = [Link]()


.flatMap(sentence ->
[Link]([Link]().split("\\s+")))
.collect([Link](word -> word,
[Link]()));

// Output: {java=2, is=2, fun=1, streams=1, are=1, powerful=2}

Q13: From a list of integers, find the duplicate numbers and how many times they occur.

List<Integer> nums = [Link](1, 2, 3, 2, 3, 4, 5, 3);

Map<Integer, Long> duplicates = [Link]()


.collect([Link]([Link](),
Sol [Link]()))
.entrySet().stream()
.filter(e -> [Link]() > 1)
.collect([Link]([Link]::getKey,
[Link]::getValue));

// Output: {2=2, 3=3}

#[Link] @codetechtone [Link] [Link]/in/pkprusty999


Q14: Flatten a Map<String, List<List<Integer>>> into a List<Integer>.
Map<String, List<List<Integer>>> map = [Link](
"a", [Link]([Link](1, 2), [Link](3)),
"b", [Link]([Link](4), [Link](5, 6))
);

List<Integer> flatList = [Link]().stream()


Sol .flatMap(List::stream)
.flatMap(List::stream)
.collect([Link]());

// Output: [1, 2, 3, 4, 5, 6]

Q15:
Return the common elements between two lists using streams.

Sol List<Integer> common = [Link]()


.filter(list2::contains)
.collect([Link]());

Q16: Remove duplicate integers from a list.


List<Integer> numbers = [Link](1, 2, 2, 3, 4, 4, 5);

Sol List<Integer> uniqueNumbers = [Link]()


.distinct()
.collect([Link]());

[Link](uniqueNumbers); // Output: [1, 2, 3, 4, 5]

Q17: Given "hello world", count the frequency of each character.

Sol Map<Character, Long> charFreq = [Link]()


.mapToObj(c -> (char) c)
.filter(c -> c != ' ')
.collect([Link]([Link](),
[Link]()));

#[Link] @codetechtone [Link] [Link]/in/pkprusty999


Q18: Given a list of strings, find the element that occurs most frequently.

List<String> input = [Link]("apple", "banana", "apple", "orange", "banana", "apple");


Sol
String mostFrequent = [Link]()
.collect([Link]([Link](),
[Link]()))
.entrySet().stream()
.max([Link]())
.map([Link]::getKey)
.orElse(null);

[Link](mostFrequent); // Output: apple

Q19: Given a list of lowercase strings, return the list of characters that appear in every string.

List<String> words = [Link]("bella", "label", "roller");


List<Character> commonChars = [Link]()
Sol .map(word -> [Link]()
.mapToObj(c -> (char) c)
.collect([Link](c -> c, [Link]())))
.reduce((map1, map2) -> {
[Link]().retainAll([Link]());
[Link]((k, v) -> [Link](v, [Link](k)));
return map1;
})
.orElse([Link]()).entrySet().stream()
.flatMap(e -> [Link]([Link]().intValue(), [Link]()).stream())
.collect([Link]());

// Output: [e, l, l]

Q20: Reverse a list of elements using streams only.

Sol List<Integer> reversed = [Link](0, [Link]())


.mapToObj(i -> [Link]([Link]() - i - 1))
.collect([Link]());

#[Link] @codetechtone [Link] [Link]/in/pkprusty999


Follow
[Link]

[Link]/in/pkprusty999

You might also like