๐ฅ 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