#
map() method
This tutorial explains how we can use map() method for Streams in Java.
map()method produces a new stream after applying a function to each element of the original streammap()method takes a lambda expression as a parameter.
Please take a look at the following example and read carefully the comments. The code is self-explanatory.
This example is created from a simple Spring Boot application created with Spring Initializr. I am using Maven, Java 17, Spring Boot 3.1.0.
From the base application downloaded from Spring Initializr, I updated the main class as below:
DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import java.util.concurrent.ExecutionException;
import java.util.stream.Stream;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// Create the application context and start Spring Boot
ApplicationContext appContext = SpringApplication.run(DemoApplication.class, args);
Integer[] numbers = { 1, 2, 3 };
Stream.of(numbers)
// We are using a simple lambda expression
.map(x -> x*100)
.forEach(p -> System.out.println(p));
System.out.println("----------------------------");
Stream.of(numbers)
// We can define a more complex lambda expression
.map(x -> {
Integer x1 = x*100;
x1 = x1 + 1;
return x1;
} )
.forEach(p -> System.out.println(p));
}
}
When I run this code I receive:
100
200
300
----------------------------
101
201
301
Process finished with exit code 0
When we are working with Streams, we can have:
- INTERMEDIATE operations:
filter,map,limit,sorted,peak,distinct,skip,flatMap - TERMINAL operations:
forEach,count,sum,min,collect,reduce,anyMatch,noneMatch,allMatch
