Java.Java8.What are the map() and mapToInt(), mapToDouble(), mapToLong() methods used for in streams?

✅ 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

MethodInput TypeReturn TypePurpose
map()T → RStream<R>General transformation
mapToInt()T → intIntStreamTransform to primitive int
mapToDouble()T → doubleDoubleStreamTransform to primitive double
mapToLong()T → longLongStreamTransform 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);
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.