Appearance
Using map
The Stream.map() method is one of the most commonly used transformation methods in Stream, converting one Stream into another.
The so-called map operation maps an operation to each element in a sequence. For example, calculating the square of x can be done using the function f(x) = x * x. If we map this function to a sequence 1, 2, 3, 4, 5, we get another sequence 1, 4, 9, 16, 25:
f(x) = x * x
│
┌───┬───┬───┬───┼───┬───┬───┬───┐
│ │ │ │ │ │ │ │ │
▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼
[ 1 2 3 4 5 6 7 8 9 ]
│ │ │ │ │ │ │ │ │
▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼
[ 1 4 9 16 25 36 49 64 81 ]As we can see, the map operation maps each element of a Stream to the result of applying the target function.
java
Stream<Integer> s = Stream.of(1, 2, 3, 4, 5);
Stream<Integer> s2 = s.map(n -> n * n);If we look at the source code of Stream, we will find that the map() method accepts an object of the Function interface, which defines an apply() method responsible for converting a type T into a type R:
java
<R> Stream<R> map(Function<? super T, ? extends R> mapper);The definition of Function is:
java
@FunctionalInterface
public interface Function<T, R> {
// Convert T type to R:
R apply(T t);
}Using map(), we can perform not only mathematical calculations but also string operations and transformations on any Java object. For example:
java
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List.of(" Apple ", " pear ", " ORANGE", " BaNaNa ")
.stream()
.map(String::trim) // Trim spaces
.map(String::toLowerCase) // Convert to lowercase
.forEach(System.out::println); // Print
}
}With several map transformations, you can write code that is simple and clear in logic.
Practice
Use map() to convert a group of String into LocalDate and print the results.
Summary
The map() method is used to map each element of a Stream to another element, converting it into a new Stream. It allows the conversion of one element type into another.