Mapping Operations

In Java 8, mapping operations in the Stream API transform elements in a stream into new elements, typically by applying a function to each element. These operations are key to functional-style programming, allowing you to convert or project data into a different form. Below are the primary mapping operations in Java 8 streams, with explanations and examples.

1. map(Function<T, R> mapper)

  • Purpose: Transforms each element in the stream into a new element of type R by applying the provided function.
  • Use Case: When you want to convert elements into a different type or format (e.g., extract a field, compute a value).
List<String> words = Arrays.asList("apple", "banana", "cherry");
words.stream()
     .map(String::toUpperCase)
     .forEach(System.out::println);

//Output
APPLE
BANANA
CHERRYCode language: PHP (php)

2. mapToInt(ToIntFunction<T> mapper)

  • Purpose: Maps each element to an int, producing an IntStream.
  • Use Case: Useful for numeric operations or when you need to work with primitive int values to avoid boxing/unboxing overhead.
  • Example:
List<String> words = Arrays.asList("apple", "banana", "cherry");
words.stream()
     .mapToInt(String::length)
     .forEach(System.out::println);
//Output
5
6
6Code language: PHP (php)

3. mapToLong(ToLongFunction<T> mapper)

  • Purpose: Maps each element to a long, producing a LongStream.
  • Use Case: When working with large numbers or long values.
  • Example:
List<String> words = Arrays.asList("apple", "banana", "cherry");
words.stream()
     .mapToLong(String::length)
     .forEach(System.out::println);
//Output
5
6
6Code language: PHP (php)

4. mapToDouble(ToDoubleFunction<T> mapper)

  • Purpose: Maps each element to a double, producing a DoubleStream.
  • Use Case: When performing floating-point computations.
  • Example:
List<String> words = Arrays.asList("apple", "banana", "cherry");
words.stream()
     .mapToDouble(str -> str.length() * 1.5)
     .forEach(System.out::println);
//Output
7.5
9.0
9.0Code language: PHP (php)

5. flatMap(Function<T, Stream<R>> mapper)

  • Purpose: Maps each element to a stream of elements (or multiple elements) and flattens the resulting streams into a single stream.

  • Use Case: When an element produces multiple elements (e.g., splitting strings, expanding collections).

  • Example:

List<String> sentences = Arrays.asList("Hello World", "Java Streams");
sentences.stream()
         .flatMap(sentence -> Arrays.stream(sentence.split(" ")))
         .forEach(System.out::println);
//Output
Hello
World
Java
StreamsCode language: PHP (php)
Example with Nested Collections:
List<List<Integer>> nestedList = Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4));
nestedList.stream()
          .flatMap(List::stream)
          .forEach(System.out::println);

//Output
1
2
3
4Code language: PHP (php)

6. flatMapToInt(Function<T, IntStream> mapper)

  • Purpose: Maps each element to an IntStream and flattens the results into a single IntStream.
  • Use Case: When mapping to primitive int streams with multiple values per element.
  • Example:
List<String> words = Arrays.asList("123", "456");
words.stream()
     .flatMapToInt(str -> str.chars())
     .forEach(ch -> System.out.println((char)ch));

//Output
1
2
3
4
5
6Code language: PHP (php)

7. flatMapToLong(Function<T, LongStream> mapper)

  • Purpose: Maps each element to a LongStream and flattens the results into a single LongStream.
  • Use Case: For long values with multiple results per element.
  • Example:
List<String> numbers = Arrays.asList("123", "456");
numbers.stream()
       .flatMapToLong(str -> str.chars().mapToLong(ch -> ch))
       .forEach(System.out::println);

//Output
49
50
51
52
53
54Code language: PHP (php)

8. flatMapToDouble(Function<T, DoubleStream> mapper)

  • Purpose: Maps each element to a DoubleStream and flattens the results into a single DoubleStream.
  • Use Case: For double values with multiple results per element.
  • Example:
     
List<String> words = Arrays.asList("1.5", "2.5");
words.stream()
     .flatMapToDouble(str -> DoubleStream.of(Double.parseDouble(str)))
     .forEach(System.out::println);

//Output
1.5
2.5Code language: PHP (php)

About Mapping Operations in Java 8

  • Intermediate Operations: All mapping operations (map, flatMap, etc.) are intermediate, meaning they return a new stream and are lazy (executed only with a terminal operation like forEach or collect).
  • Function Application: Mapping operations rely on functional interfaces (Function, ToIntFunction, etc.) to define the transformation logic.
  • Type Transformation:
    • map can change the type of elements (e.g., String to Integer).
    • flatMap is used for one-to-many transformations, flattening nested structures.
    • Primitive mappings (mapToInt, mapToLong, mapToDouble) optimize performance by avoiding boxing/unboxing.
  • Order Matters: Mapping operations are applied in the order they appear in the stream pipeline.
  • Stateless: Mapping operations are stateless, meaning each element is processed independently.

Common Use Cases

  • Data Transformation: Converting objects to a different type (e.g., extracting fields from objects).
  • Flattening Structures: Handling nested collections or arrays (e.g., splitting strings into words).
  • Primitive Optimization: Using mapToInt, mapToLong, or mapToDouble for performance in numeric computations.
  • Preprocessing: Preparing data for further operations like filtering or collecting.

Mapping operations in Java Streams are essential for manipulating and transforming data efficiently and succinctly, making them a cornerstone of modern Java programming for data processing tasks.

Scroll to Top