✅ 1. map(Function<T, R>)
🔧 Purpose:
Transforms each element of the stream using a function, returning a new stream of possibly different type.
Stream<String> names = Stream.of("Stan", "Alex");
Stream<Integer> lengths = names.map(String::length);
Input: T
Output: R
Returns: Stream<R>
✅ 2. mapToInt(ToIntFunction<T>)
🔧 Purpose:
Maps elements to primitive int
values, and returns an IntStream
.
Stream<String> names = Stream.of("Java", "Python");
IntStream lengths = names.mapToInt(String::length); // avoids boxing!
Efficient: avoids creating boxed Integer
objects
Ideal for use with .sum()
, .average()
, .max()
, etc.
✅ 3. mapToDouble(ToDoubleFunction<T>)
🔧 Purpose:
Maps elements to primitive double
values → returns a DoubleStream
Stream<String> words = Stream.of("a", "ab", "abc");
DoubleStream score = words.mapToDouble(w -> w.length() * 1.5);
✅ 4. mapToLong(ToLongFunction<T>)
🔧 Purpose:
Maps elements to primitive long
values → returns a LongStream
Stream<String> items = Stream.of("apple", "banana");
LongStream longs = items.mapToLong(s -> (long) s.length());
📦 Summary Table
Method | Input Type | Return Type | Purpose |
---|---|---|---|
map() | T → R | Stream<R> | General transformation |
mapToInt() | T → int | IntStream | Transform to primitive int |
mapToDouble() | T → double | DoubleStream | Transform to primitive double |
mapToLong() | T → long | LongStream | Transform to primitive long |
💡 When to use primitive variants?
Use mapToInt
, mapToDouble
, or mapToLong
when:
✅ You want to avoid boxing
✅ You need to use primitive stream methods like .sum()
, .average()
, .summaryStatistics()
✅ You’re doing numeric computation in performance-sensitive code
🧠 Example: Comparing map()
vs mapToInt()
// Less efficient: creates Integer objects
int total = Stream.of("a", "bb", "ccc")
.map(s -> s.length())
.reduce(0, Integer::sum);
// Better: avoids boxing
int total2 = Stream.of("a", "bb", "ccc")
.mapToInt(String::length)
.sum();
✅ Bonus: You can also convert back
IntStream.range(1, 5)
.mapToObj(i -> "Item" + i) // returns Stream<String>
.forEach(System.out::println);