๐ฅ Q1: What's the output of this?
โ Answer:
Output:
-
word.split("")
โ givesString[]
-
map()
givesStream<String[]>
-
flatMap(Arrays::stream)
flattensStream<String[]>
โStream<String>
-
distinct()
removes duplicates
๐ฅ Trick: map(Arrays::stream)
would give you Stream<Stream<String>>
and fail to compile in .collect()
.
๐ฅ Q2: Why does this not compile?
โ Answer:
It compiles, but the result is List<Stream<Integer>>
, not List<Integer>
.
To flatten the list, use:
๐ Trick: flatMap
is needed to flatten nested streams.
๐ฅ Q3: How is flatMap()
different from map()
in Optional?
โ Answer:
-
map()
โ wraps result โOptional<Optional<String>>
-
flatMap()
โ avoids wrapping โOptional<String>
๐ง Trick: Use flatMap
when the function already returns an Optional
.
๐ฅ Q4: What happens here?
โ Answer:
๐ฅ Runtime Exception: IllegalStateException: stream has already been operated upon or closed
Why? Because map()
doesnโt mutate the original stream โ it returns a new one. But it was never assigned.
๐ง Trick: Streams are one-time use. Always assign or chain after map()
or flatMap()
.
๐ฅ Q5: Can you convert a List<String>
where each string is comma-separated into a List<String>
of all elements?
โ Answer:
Yes, with flatMap()
:
Output:
๐ก Trick: split()
gives arrays. Need flatMap(Arrays::stream)
to flatten.
๐ฅ Q6: Whatโs the output?
โ Answer:
-
mapped.size()
โ 3 -
mapped.get(0)[0]
โ"a"
๐ง Trick: map()
does not flatten โ you still have a List<String[]>
, not a flat List<String>
. Only flatMap()
can do that.
๐ฅ Q7: What does this do?
โ Answer:
-
It creates a
Stream<Stream<Character>>
-
Each inner stream represents characters of a string
โ
If you want a flat Stream<Character>
:
๐ฅ Trick: Interviewers love chars + streams + mapping โ always pay attention to return types.
๐ฅ Q8: Can you use flatMap()
with primitives?
โ Answer:
Yes, but carefully! Primitives like IntStream
, LongStream
etc. don't work directly with flatMap
.
Example:
๐ฅ Trick: To flatMap a primitive stream, use:
๐ฅ Q9: Which is more efficient: map().flatMap()
vs flatMap()
directly?
โ Answer:
-
If you're nesting transformations (e.g.
map().map()
), it's fine. -
But if you're mapping and flattening,
flatMap()
is better.
Bad:
Better:
๐ฅ Trick: .flatMap()
avoids intermediate structures (like List of Lists) โ better for performance and memory.
๐ฅ Q10: What if flatMap returns null?
โ Answer:
๐ฅ NullPointerException
โ You cannot return null
from a flatMap
โ it must return a valid Stream
. If you want an empty result, return Stream.empty()
.
Correct way:
๐ฅ Trick: Always return a Stream, even if itโs empty. No null
allowed in flatMap()
.
๐งช Final Trick:
"Use
map()
when you transform values. UseflatMap()
when you're dealing with nested structures (like lists of lists or Optionals of Optionals)."
No comments:
Post a Comment