Sobes.tech
Middle

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 type T into a stream of objects of type R. mapper is a function that takes an element of type T and returns an element of type R.

    // 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 type T into a specialized stream of primitive int values (IntStream). mapper is a function that takes an element of type T and returns an int.

    // 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 type T into a specialized stream of primitive double values (DoubleStream). mapper is a function that takes an element of type T and returns a double.

    // 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 type T into a specialized stream of primitive long values (LongStream). mapper is a function that takes an element of type T and returns a long.

    // 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.