Java Collectors mapping() Method

The mapping() method in Java, part of the java.util.stream.Collectors class, is used to apply a mapping function to the elements of a stream before collecting them. This method is useful when you need to transform the elements of a stream and then collect the transformed elements.

Table of Contents

  1. Introduction
  2. mapping() Method Syntax
  3. Understanding mapping()
  4. Examples
    • Basic Usage
    • Using mapping() with GroupingBy
  5. Real-World Use Case
  6. Conclusion

Introduction

The mapping() method returns a Collector that applies a mapping function to each element before passing the results to a downstream collector. This method is particularly useful when you need to transform the elements of a stream and then collect the transformed elements.

mapping() Method Syntax

The syntax for the mapping() method is as follows:

public static <T, U, A, R> Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper, Collector<? super U, A, R> downstream)

Parameters:

  • mapper: A function that maps elements of type T to elements of type U.
  • downstream: A Collector that collects the mapped elements.

Returns:

  • A Collector that applies the mapping function and collects the mapped elements.

Throws:

  • This method does not throw any exceptions.

Understanding mapping()

The mapping() method allows you to transform the elements of a stream using a specified mapping function before collecting them. This is useful in scenarios where you need to modify the elements of a stream and then collect the modified elements.

Examples

Basic Usage

To demonstrate the basic usage of mapping(), we will create a list of integers, square each element using a mapping function, and then collect the squared elements into a list.

Example

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MappingExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        // Square each element and collect the squared elements into a list
        List<Integer> squaredNumbers = numbers.stream()
                                              .collect(Collectors.mapping(
                                                  n -> n * n,
                                                  Collectors.toList()
                                              ));

        System.out.println("Squared Numbers: " + squaredNumbers);
    }
}

Output:

Squared Numbers: [1, 4, 9, 16, 25]

Using mapping() with GroupingBy

This example shows how to use mapping() in conjunction with groupingBy to group elements by their length and collect the uppercase versions of the strings in each group.

Example

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MappingWithGroupingByExample {
    public static void main(String[] args) {
        List<String> words = Arrays.asList("apple", "banana", "cherry", "date", "fig", "grape");

        // Group words by their length and collect the uppercase versions of the words in each group
        Map<Integer, List<String>> groupedByLength = words.stream()
                                                          .collect(Collectors.groupingBy(
                                                              String::length,
                                                              Collectors.mapping(
                                                                  String::toUpperCase,
                                                                  Collectors.toList()
                                                              )
                                                          ));

        System.out.println("Grouped by Length with Uppercase: " + groupedByLength);
    }
}

Output:

Grouped by Length with Uppercase: {3=[FIG], 4=[DATE], 5=[APPLE, GRAPE], 6=[BANANA, CHERRY]}

Real-World Use Case

Extracting and Collecting Names

In real-world applications, the mapping() method can be used to extract and collect specific properties of objects. For example, extracting and collecting the names of people from a list of Person objects.

Example

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ExtractingNamesExample {
    static class Person {
        String name;
        int age;

        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        String getName() {
            return name;
        }
    }

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Alice", 30),
            new Person("Bob", 25),
            new Person("Charlie", 35)
        );

        // Extract and collect the names of people
        List<String> names = people.stream()
                                   .collect(Collectors.mapping(
                                       Person::getName,
                                       Collectors.toList()
                                   ));

        System.out.println("Names: " + names);
    }
}

Output:

Names: [Alice, Bob, Charlie]

Conclusion

The Collectors.mapping() method is used to apply a mapping function to the elements of a stream before collecting them. This method is particularly useful for transforming elements and then collecting the transformed elements. By understanding and using this method, you can efficiently manage mapping and collection operations in your Java applications.

Comments