What are the purposes of the methods map(), mapToInt(), mapToDouble(), and mapToLong() in streams?
sobes.tech AI
Answer from AI
These methods are used to transform stream elements from one type to another. They apply a function to each element and return a new stream with the transformed elements.
-
map(Function<? super T, ? extends R> mapper): Converts a stream of objects of typeTinto a stream of objects of typeR.mapperis a function that takes an element of typeTand returns an element of typeR.// Example: transforming a stream of strings into their lengths List<String> words = Arrays.asList("hello", "world"); Stream<Integer> lengths = words.stream() .map(String::length); -
mapToInt(ToIntFunction<? super T> mapper): Converts a stream of objects of typeTinto a specialized stream of primitiveintvalues (IntStream).mapperis a function that takes an element of typeTand returns anint.// Example: transforming a stream of strings into their hash codes (int) List<String> words = Arrays.asList("hello", "world"); IntStream hashCodes = words.stream() .mapToInt(String::hashCode); -
mapToDouble(ToDoubleFunction<? super T> mapper): Converts a stream of objects of typeTinto a specialized stream of primitivedoublevalues (DoubleStream).mapperis a function that takes an element of typeTand returns adouble.// Example: transforming a stream of strings into their length as double List<String> words = Arrays.asList("hello", "world"); DoubleStream doubleLengths = words.stream() .mapToDouble(String::length); // Result will be double -
mapToLong(ToLongFunction<? super T> mapper): Converts a stream of objects of typeTinto a specialized stream of primitivelongvalues (LongStream).mapperis a function that takes an element of typeTand returns along.// Example: transforming a stream of strings into their length as long List<String> words = Arrays.asList("hello", "world"); LongStream longLengths = words.stream() .mapToLong(String::length); // Result will be long
Using mapToInt, mapToDouble, and mapToLong is preferable when the transformation result is a primitive numeric type, as they work with more efficient specialized streams that avoid boxing/unboxing primitives.