In Java 8, the Stream map()
method is used for transforming elements in a stream. It takes Function
as an argument and applies that function to each element in the stream, producing a new stream with the transformed elements. In this post, we going to explore and see Java 8 Stream map() Examples.
Syntax for Java Stream map() method:-
Stream<T> map(Function<? super T, ? extends R> mapper)
T
: The type of the elements in the original stream.R
: The type of the elements in the resulting stream.mapper
: A function that takes an element of typeT
from the original stream and returns an element of typeR
for the resulting stream.
The map()
method in Java Streams is mainly used when we need to transform the elements of a stream from one type to another or apply some operation to each element of the stream and generate a new stream of the transformed elements. Check how the map() method is different from than filter() method.
Example – We have a list of numbers and we want to increase each number by 50.
package com.javatute.stream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class JavaStreamMapExample {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(35);
list.add(5);
list.add(33);
list.add(24);
list.add(3);
list.add(20);
System.out.println(list);
List<Integer> increaseValueByFifty = list.stream().map(n -> n + 50).collect(Collectors.toList());
System.out.println(increaseValueByFifty);
}
}
Output:-
[10, 35, 5, 33, 24, 3, 20]
[60, 85, 55, 83, 74, 53, 70]
Here are some common scenarios when we might want to use the map()
method.
- Data Transformation: We have a stream of data, and we want to convert each element into a different form or type. For example, converting a stream of strings to uppercase or parsing strings into numbers.
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
// Transforming names to uppercase
List<String> upperCaseNames = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
- Extracting a Property: Consider we have a stream of objects and we want to extract a specific property from each object to work with.
class Person {
private String name;
// Constructor and getters here...
}
List<Person> people = Arrays.asList(new Person("Alice"), new Person("Bob"), new Person("Charlie"));
// Extracting names from Person objects
List<String> names = people.stream()
.map(Person::getName)
.collect(Collectors.toList());
- Calculating Derived Values: Suppose we want to calculate some derived values based on the elements in the stream. For example, calculating the square of each number in a stream of integers.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Calculating squares of numbers
List<Integer> squares = numbers.stream()
.map(x -> x * x)
.collect(Collectors.toList());
- Custom Object Transformation: Consider we want to map one type of object to another type, e.g., mapping DTOs (Data Transfer Objects) to domain objects.
class PersonDTO {
private String name;
// Constructor and getters here...
}
List<PersonDTO> dtos = Arrays.asList(new PersonDTO("Alice"), new PersonDTO("Bob"));
// Mapping PersonDTO to Person objects
List<Person> people = dtos.stream()
.map(dto -> new Person(dto.getName()))
.collect(Collectors.toList());
- Filtering and Mapping: Combining
filter()
andmap()
can be useful when we want to filter elements based on a condition and then map the filtered elements.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Filter even numbers and then map them to squares
List<Integer> evenSquares = numbers.stream()
.filter(x -> x % 2 == 0)
.map(x -> x * x)
.collect(Collectors.toList());
In summary, we should use the map()
method when we need to transform, extract, or derive values from the elements of a stream to create a new stream of modified elements. It’s a fundamental operation in functional programming and is often used in conjunction with other stream operations to process and manipulate data efficiently.
Here are five different Java 8 Stream map()
examples, both with and without Java 8, including examples with custom objects.
1. Map a list of integers to their squared values:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class MapExample1 {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Without Java 8
for (Integer num : numbers) {
System.out.print(num * num + " ");
}
System.out.println();
// With Java 8
List<Integer> squaredNumbers = numbers.stream()
.map(n -> n * n)
.collect(Collectors.toList());
squaredNumbers.forEach(n -> System.out.print(n + " "));
}
}
Output:
1 4 9 16 25
1 4 9 16 25
2. Map a list of strings to their lengths:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class MapExample2 {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry", "date");
// Without Java 8
for (String word : words) {
System.out.print(word.length() + " ");
}
System.out.println();
// With Java 8
List<Integer> wordLengths = words.stream()
.map(String::length)
.collect(Collectors.toList());
wordLengths.forEach(len -> System.out.print(len + " "));
}
}
Output:
5 6 6 4
5 6 6 4
3. Map a list of custom objects to a specific property:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class MapExample3 {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 35)
);
// Without Java 8
for (Person person : people) {
System.out.print(person.getName() + " ");
}
System.out.println();
// With Java 8
List<String> names = people.stream()
.map(Person::getName)
.collect(Collectors.toList());
names.forEach(name -> System.out.print(name + " "));
}
}
Output:
Alice Bob Charlie
Alice Bob Charlie
4. Map a list of custom objects to a derived property:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public double getPrice() {
return price;
}
}
public class MapExample4 {
public static void main(String[] args) {
List<Product> products = Arrays.asList(
new Product("Laptop", 999.99),
new Product("Smartphone", 399.99),
new Product("Tablet", 299.99)
);
// Without Java 8
for (Product product : products) {
System.out.print(product.getPrice() * 2 + " ");
}
System.out.println();
// With Java 8
List<Double> doubledPrices = products.stream()
.map(p -> p.getPrice() * 2)
.collect(Collectors.toList());
doubledPrices.forEach(price -> System.out.print(price + " "));
}
}
Output:
1999.98 799.98 599.98
1999.98 799.98 599.98
5. Map a list of strings to uppercase:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class MapExample5 {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry", "date");
// Without Java 8
for (String word : words) {
System.out.print(word.toUpperCase() + " ");
}
System.out.println();
// With Java 8
List<String> uppercasedWords = words.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
uppercasedWords.forEach(word -> System.out.print(word + " "));
}
}
Output:
APPLE BANANA CHERRY DATE
APPLE BANANA CHERRY DATE
These examples demonstrate how to use the map()
operation in Java 8 Streams to transform data in various ways, including with custom objects.
Let’s see a few important points related to the Java 8 Stream map() method.
- Transformation: The
map()
method is used to transform the elements of a stream from one type to another or apply a function to each element in the stream to produce a new stream of transformed elements. - Function as Argument: It takes a
Function
as an argument, which defines how each element in the stream should be transformed. This function is applied to every element in the stream. - Lazy Evaluation: Streams in Java 8 are lazily evaluated, which means that the
map()
operation is not performed until a terminal operation (e.g.,collect()
,forEach()
,reduce()
) is invoked on the stream. This allows for efficient processing of large datasets. - Immutable: The
map()
operation does not modify the original stream. Instead, it creates a new stream with the transformed elements, leaving the original stream unchanged. - Type Transformation: It is commonly used for type conversion, such as converting a stream of strings to uppercase, parsing strings to numbers, or mapping objects to their properties.
- Intermediate Operation:
map()
is an intermediate operation, which means it can be followed by other stream operations likefilter()
,sorted()
, or even anothermap()
, allowing you to build complex data processing pipelines. - Examples: Common use cases include mapping DTOs (Data Transfer Objects) to domain objects, extracting specific properties from objects, and performing mathematical operations on elements in a stream.
- Functional Programming: The
map()
method is a fundamental tool in functional programming paradigms, where data transformations are expressed as functions. - Parallelism: When used in parallel streams, the
map()
operation can take advantage of multi-core processors to perform transformations concurrently, potentially improving performance for CPU-bound operations. - Common Alternatives: In addition to
map()
, Java Streams offer other transformation methods likeflatMap()
, which can be used when you need to map each element to multiple elements or flatten nested streams.
Overall, the map()
method is a versatile and powerful tool for data transformation in Java 8 Streams, allowing you to elegantly manipulate and process data in a functional and declarative manner.
Ten objective questions related to Java 8 Stream map() Examples.
1. What is the purpose of the map()
method in Java 8 Streams?
- A) To filter elements in a stream.
- B) To transform each element in a stream.
- C) To reduce elements in a stream.
- D) To check if an element exists in a stream.
2. Which interface does the map()
method belong to in Java 8 Streams?
- A) Collection
- B) Iterable
- C) Stream
- D) Map
3. In the context of Java 8 Streams, what does the map()
method return?
- A) A single value
- B) A new stream with transformed elements
- C) An exception
- D) A boolean value
4. What is the correct syntax for using the map()
method in a Java 8 Stream?
- A)
stream.map(Function<T, R> mapper)
- B)
stream.mapTo(Function<T, R> mapper)
- C)
stream.mapWith(Function<T, R> mapper)
- D)
stream.transform(Function<T, R> mapper)
5. When using map()
, what does the provided mapper function do?
- A) Filters elements in the stream.
- B) Converts elements to uppercase.
- C) Performs a reduction operation.
- D) Transforms each element in the stream.
6. Which of the following statements is true about the map()
operation in Java 8 Streams?
- A) It can only be applied to numeric streams.
- B) It modifies the original stream in place.
- C) It can be used to transform elements based on a provided function.
- D) It can be used for parallel processing only.
7. What type of values can be returned by the map()
operation when applied to a stream of objects?
- A) Only objects of the same type
- B) Any type of objects
- C) Only primitive data types
- D) Only null values
8. In Java 8, what does the collect(Collectors.toList())
method typically do after using map()
on a stream?
- A) Sum the elements in the stream.
- B) Convert the stream into an array.
- C) Collect the transformed elements into a List.
- D) Sort the elements in the stream.
9. What is the primary benefit of using the map()
method in Java 8 Streams?
- A) It reduces the number of elements in a stream.
- B) It simplifies exception handling.
- C) It allows for efficient element transformation.
- D) It converts a stream into an array.
10. Which of the following statements is true about the order of elements in the resulting stream when using map()
?
– A) The order is guaranteed to be the same as the original stream.
– B) The order is random and cannot be predicted.
– C) The order depends on the order in which elements are processed.
– D) The order is reversed compared to the original stream.
Answers:
- B) To transform each element in a stream.
- C) Stream
- B) A new stream with transformed elements
- A)
stream.map(Function<T, R> mapper)
- D) Transforms each element in the stream.
- C) It can be used to transform elements based on a provided function.
- B) Any type of objects
- C) Collect the transformed elements into a List.
- C) It allows for efficient element transformation.
- C) The order depends on the order in which elements are processed.
That’s all about Java 8 Stream map() Examples.
See Java 8 Stream map() method docs.
Other Java 8 examples.