InterviewVault
Welcome back, Sujit Kumar Mishra
Admin
SK Mishra
Revision Mode
Document technical questions and best-practice answers.
Stream API Mapping
- In the Stream API, what is the difference between map() and mapToObj()?
- When should each be used?
Stream API Mapping: map() vs mapToObj()
1: map() is used to transform each element in a stream to another value. For example, you can convert a list of numbers to their squares.
2: mapToObj() is used when you are working with primitive streams (like IntStream, DoubleStream) and want to convert them to an object stream (Stream of objects).
When to use:
1: Use map() for regular streams (Stream) when you want to change the value but keep it as an object.
2: Use mapToObj() for primitive streams (like IntStream) when you want to turn primitives into objects.
Easy way to remember:
map() = change objects to other objects.
mapToObj() = change primitives to objects.
Example:
Stream<String>.map(String::length) → Stream
IntStream.mapToObj(i -> "Number: " + i) → Stream
Summary:
Use map() for object streams, mapToObj() for primitive streams to convert to objects.