0% found this document useful (0 votes)
8 views16 pages

Java Stream API

The Java Stream API, introduced in Java 8, facilitates functional programming by providing a clean and efficient way to process data through a pipeline of operations. It consists of stream sources, intermediate operations (which are lazy), and terminal operations (which are eager), allowing for cleaner code and improved performance. The API is best suited for stateless data processing and should be avoided in scenarios requiring mutable state or complex control flow.

Uploaded by

banosawaira4
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)
8 views16 pages

Java Stream API

The Java Stream API, introduced in Java 8, facilitates functional programming by providing a clean and efficient way to process data through a pipeline of operations. It consists of stream sources, intermediate operations (which are lazy), and terminal operations (which are eager), allowing for cleaner code and improved performance. The API is best suited for stateless data processing and should be avoided in scenarios requiring mutable state or complex control flow.

Uploaded by

banosawaira4
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

Stream api:

The Java Stream API, Introduced in Java 8 to support functional programming. It eliminates
repetitive boilerplate code and makes code cleaner.

A Stream is not a data structure. It doesn’t store elements — it acts as a data pipeline that
pulls data from sources like Lists, Maps, Sets, Arrays, and I/O channels, and processes them
through a series of operations.

Internal Working Flow of Stream


(Stream Source → Intermediate Operations → Terminal Operation)

• Stream Source: Data is collected from a List, Map, Set, Arrays, etc.
• Intermediate Operations (Lazy) :
operations that transform one stream into another stream, and, crucially, are lazy This
means they are not executed until a terminal operation is invoked on the stream pipeline
Operation Description Example
filter() Selects elements that match a given predicate [Link]().filter(s -> [Link]() > 5)
(a condition)
map() one-to-one transformation [Link]().map(String::toUpperCase)
Convert each element of a stream into exactly
one other element
flatMap() one-to-many transformation [Link]().flatMap(Set::stream)
Convert each element into zero or more
elements, and flatten nested streams into a
single stream
distinct() Returns a stream with unique elements [Link]().distinct()
(removes duplicates)
sorted() Sorts the elements in the stream, either [Link]().sorted()
naturally or using a custom Comparator
peek() Performs an action on each element as it [Link]().peek([Link]::println)
passes through the pipeline, primarily used for
logging, debugging, or monitoring
limit() Truncates the stream to contain no more than a [Link]().limit(10)
specified number of elements
skip() Discards the first n elements of the stream [Link]().skip(5)
• Terminal Operations (Eager) : are the final action in a stream pipeline that trigger the
execution of all chained intermediate operations.

reduce(), forEach(), min(), count(),collect(),toArray() ,findFirst(),findAny() , noneMatch() ,


allMatch() , anyMatch() , sum(), average(), summaryStatistics() , min() / max() , count()

Difference Between Intermediate and Terminal Operations:

Uses of Stream API:


• Cleaner, readable, and maintainable code
• Lazy execution improves performance
• Easy parallelism (parallelStream())
• Safe functional operations (no modification of source data)

Parallel Streams
• Uses [Link]()
• Good for CPU-heavy operations
• Avoid with:
• small collections
• mutable shared data
• I/O tasks o ordered operations

When not to use Stream:

Rule 1: When you need to remember the previous element


Ex: Longest contiguous increasing sequence

Rule 2: When logic depends on index (i, i+1)


Ex: Sliding window , Pair comparisons , Accessing neighbors
Rule 3: When you need to break early
Ex. Stop when value > 100, exit loop at some condition
Rule 4: When code becomes unreadable

Rule 5: When state is mutated


Ex. Modifying shared variables, Complex counters

Mutating : changing external/shared state inside a stream operation.


If your lambda changes something outside it, you are mutating state — don’t use Streams.
Ex: int sum = 0;
[Link]().forEach(n -> sum += n); // mutation

Stateless: “Operation does not depend on previously processed elements.”


They don’t use memory , paralley safe, fast
Ex: map(), filter(), flatMap(), peek() (only for observing)

Stateful: “Operation depends on or stores previous elements.”


They use memory, not parallel safe, slower

Ex: distinct(), sorted(), limit(), skip()

Use the Stream API for declarative, stateless data processing pipelines. Avoid it for simple
loops, mutable logic, or performance-critical sections.

Streams are best for data flow, while loops are better for control flow.

Some Questions:

1) Check if a String is a palindrome using Stream API


Input: "madam" and Output: true

2) Reverse a each word in a sentence using stream api.


Input: All power is within you
Output : llA rewop si nihtiw uoy
3) Reverse a string using stream api:

4) Given a list of words, return the longest word using Streams.


Input: ["apple", "banana", "kiwi", "strawberry"] Output: "strawberry"

5) Remove duplicate characters from a String (preserve order)


Input: "banana" Output: "ban"

6) Find duplicate characters in a String


Input: "programming" Output: r, g, m

7) Given a list of strings, return a list of strings that contain at least one vowel, converted to
uppercase, and sorted alphabetically.
Input: ["sky", "apple", "rhythm", "orange", "fly", "umbrella"]
Output: ["APPLE", "ORANGE", "UMBRELLA"]

8) Sum of all elements in an array:

Boxed - Primitive → Object Stream 39.

9) Given a list of integers, filter even numbers, square them, sort them, and return the result.

10) Check if two Strings are anagrams using Stream API


Input: "listen", "silent"
Output: true

11) Find the longest word in a sentence using Stream API


Input: "I'm a java developer" Output: “developer”
12) Check if a given string has all unique characters using Stream API.
Input: "java Output: false // 'a' repeats
Input: "python" Output: true // all characters unique

13) Find the first repeated character in a String

Input: "programming" and Output: "r"

14) Given a list of names, return a list of names that start with “A”, sorted alphabetically.
Input: ["Raju", "Anil", "Arun", "Mahesh", "Ajay"]
Output: ["Ajay", "Anil", "Arun"]

15) From a list of strings, extract only those with length > 5, transform to uppercase, and join into
a single comma-separated string

16) Given a list of integers, return the sum of all numbers greater than 50.
Input: [10, 55, 73, 21, 99, 4]
Output : 227

17) Given a list of integers, return a new list containing only the first 3 distinct even numbers,
sorted in ascending order.
Input: [10, 4, 2, 4, 7, 12, 2, 30, 5, 12]
Output: [2, 4, 10]
18) Given a list of integers, return the longest contiguous increasing subsequence as a list.
Input: [1, 2, 3, 1, 2, 3, 4, 0, 5, 6]
Output: [1, 2, 3, 4]

19) Merge two Lists and remove duplicates.

20) Capitalize the first letter of each word using Stream API
Input: "java stream api" Output: Java Stream Api

21) Given a list of sentences, return all unique words (case-insensitive) sorted alphabetically.
Input: ["Java is fun", "Stream API is powerful"] Output: [api, fun, is, java, powerful, stream]
22) Sum all integers in List<List<Integer>> using reduce.
Input: [[1,2], [3,4,5], [6]] Output: 21

23) From a list of integers, replace every odd number with -1, keep evens unchanged.
Input: [1, 2, 3, 4, 5] Output: [-1, 2, -1, 4, -1]

reduce(): combines all elements of a stream into a single result by repeatedly applying a
function.
Sum, product, min, max

24) Return the product of all even numbers greater than 3.


Input: [1, 2, 3, 4, 6, 7, 8] Output: 192 (4 × 6 × 8)

25) Compute the sum of squares of all integers in a list.


Input: [1, 2, 3, 4] Output: 30 → (1² + 2² + 3² + 4²)

26) Concatenate all strings in a list separated by –


Input: ["Java", "Stream", "API"] Ouput : "Java-Stream-API"
27) Find the maximum number in a list using reduce.
Input: [10, 2, 30, 4] Output: 30

28) Multiply all numbers in a list using parallelStream safely.


Input: [1, 2, 3, 4] Output: 24

Frequency using Collectors ONLY:

Core Frequency Pattern :

Map<T, Long> freq =


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

29) Convert a list of words into a map where each word is the key and its length is the value.
input : ["apple", "banana", "kiwi"]
output : {apple=5, banana=6, kiwi=4}

30) Given a list of integers, return a list of numbers that appear more than once (duplicates),
sorted in ascending order.
Input: [4, 2, 7, 2, 9, 4, 4] output:[2,4]
31) Given a list of strings, return all strings whose character-frequency sum is even,
convert them to lowercase, remove duplicates, sort them in reverse alphabetical order.

Input : ["Apple", "Banana", "Kiwi", "Cherry", "Mango", "Banana"]


Output: ["mango", "banana"]

32) Given a list of integers, return the top 3 most frequent numbers, sorted by frequency
descending and value ascending.
Input : [4, 4, 1, 2, 2, 2, 3, 3, 5, 5, 5, 5]
output : [5, 2, 4]

33) First non repeated character in a given String


Input: "Stress" Output: 't'
“For frequency problems, We use groupingBy with counting as a downstream collector.
If order matters, I switch to LinkedHashMap”

34) Count vowels in a String using Stream API

Input: "Java Stream API" output : 5

35) Given a list of sentences, return a Map where key = word length value = list of unique words
of that length
Input: "Java is fun", "Stream API is powerful"
Output: { 2=[is], 3=[api, java], 6=[stream], 8=[powerful] }

36) Most Frequent Element


Input: [1, 2, 3, 3, 3, 4] Output: 3
37) Top K Frequent Elements
Input: [ 1, 2 ,5 ,5, 3, 3, 3, 4 ] Output: [3, 5, 1]

Sorting:

38) Given an array of integers, print the frequency of each element sorted by frequency in ascending
order.
Input : { 4, 2, 7, 2, 9, 4, 4 }; Output : [7->1 9->1 2->2 4->3]

39) Frequency DESC + Value ASC (Tie-Breaker)

Input : { 4, 2, 7, 2, 9, 4, 4 }; Output : [4 → 3 2 → 2 7 → 2 9 → 1]

40) Frequency ASC + Value DESC (Reverse Tie-Breaker)


Input : { 4, 2, 7, 2, 9, 4, 4 }; Output : [9->1 7->1 2->2 4->3]
41) Sort Words by Frequency then Alphabetically -- first frequency . 2nd Alphabetically only when
frequencies are equal
Input : ["java", "stream", "api", "java", "api", "java", "stream"] Output: [[java, api, stream]

42) Sort by value DESC, then collect back to a Map

43) Sort characters by frequency


Input: "tree" → Output: "eert"

anyMatch() — At least one


allMatch() — Every element
noneMatch() — Zero elements - used in validation, authorization, security
44) Find words containing at least one vowel

45) Consider we have employee entity: using which we will perform some Stream operations.

You might also like