π₯ 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)."