Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Transforming Elements with the map() Method | Operações Intermediárias na Stream API
Stream API

Transforming Elements with the map() Method

Deslize para mostrar o menu

You're already familiar with the concept of intermediate operations in the Stream API. These operations transform stream elements and return a new stream without modifying the original one. One such method is map().

Note
Definition

In Java's Stream API, the map method is a powerful tool for transforming stream elements. It applies a function to each element, producing a new stream with the transformed results.

The map() method takes a Function, which is applied to every element in the stream. The results are collected into a new stream, while the original stream remains unchanged:

Stream<T> map(Function<? super T, ? extends R> mapper);
  • T – the type of elements in the original stream;
  • R – the type of elements in the new stream (after transformation).

Essentially, we pass a type T, which gets transformed into type R. That's why we use map() when we need to change the data type of a stream.

Note
Note

You can pass a Function in different ways, such as method references, lambda expressions, or by creating a custom Function (as you covered earlier).

Practical Application

Let's say you need to adjust a list of prices by adding a 10% tax to each one. This is a common scenario in financial calculations, such as applying sales tax to product prices.

Main.java

Main.java

1234567891011121314151617
package com.example; import java.util.List; import java.util.Arrays; public class Main { public static void main(String[] args) { List<Double> prices = Arrays.asList(100.0, 200.0, 50.0); // Apply a 10% tax to each price List<Double> finalPrices = prices.stream() .map(price -> price * 1.1) .toList(); System.out.println(finalPrices); } }
Note
Note

You will learn to use terminal operations in the next section, so in this example, you used a basic terminal operation, toList(), which converts the stream into a List.

In this example, each price in the list is increased by 10% using the map() method.

You multiply each value by 1.1 to account for the tax and collect the results into a new list. This transformed list can then be used for further calculations, such as generating invoices or financial reports.

Primitive Type

Note
Definition

Stream API provides specialized primitive streams: IntStream, LongStream, and DoubleStream. These allow direct operations on numbers without wrapping them in objects like Integer, Long, or Double.

Unlike the regular map method, which returns a stream of objects, mapToInt(), mapToLong(), and mapToDouble() return streams of primitive types, reducing memory overhead and improving performance.

Practical Example

The following example converts a list of numeric strings into primitive streams and prints the values.

Main.java

Main.java

1234567891011121314151617181920212223242526272829303132
package com.example; import java.util.List; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.DoubleStream; public class Main { public static void main(String[] args) { List<String> numbers = List.of("10", "20", "30", "40"); // Convert to `IntStream` IntStream intStream = numbers.stream() .mapToInt(Integer::parseInt); System.out.print("IntStream: "); intStream.forEach(n -> System.out.print(n + " ")); System.out.println(); // Convert to `LongStream` LongStream longStream = numbers.stream() .mapToLong(Long::parseLong); System.out.print("LongStream: "); longStream.forEach(n -> System.out.print(n + " ")); System.out.println(); // Convert to `DoubleStream` DoubleStream doubleStream = numbers.stream() .mapToDouble(Double::parseDouble); System.out.print("DoubleStream: "); doubleStream.forEach(n -> System.out.print(n + " ")); } }

This example processes a list of numeric strings.

First, mapToInt() converts the values into an IntStream, printing each number as an integer. Next, mapToLong() creates a LongStream, maintaining the same numerical values but in the long type. Finally, mapToDouble() transforms the data into a DoubleStream, converting the integers into decimal numbers.

Using primitive streams ensures efficient handling of numerical data while avoiding unnecessary object creation.

1. What does the map() method do in the Stream API?

2. What type of functional interface should the map() method accept?

question mark

What does the map() method do in the Stream API?

Selecione a resposta correta

question mark

What type of functional interface should the map() method accept?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 1

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Transforming Elements with the map() Method

You're already familiar with the concept of intermediate operations in the Stream API. These operations transform stream elements and return a new stream without modifying the original one. One such method is map().

Note
Definition

In Java's Stream API, the map method is a powerful tool for transforming stream elements. It applies a function to each element, producing a new stream with the transformed results.

The map() method takes a Function, which is applied to every element in the stream. The results are collected into a new stream, while the original stream remains unchanged:

Stream<T> map(Function<? super T, ? extends R> mapper);
  • T – the type of elements in the original stream;
  • R – the type of elements in the new stream (after transformation).

Essentially, we pass a type T, which gets transformed into type R. That's why we use map() when we need to change the data type of a stream.

Note
Note

You can pass a Function in different ways, such as method references, lambda expressions, or by creating a custom Function (as you covered earlier).

Practical Application

Let's say you need to adjust a list of prices by adding a 10% tax to each one. This is a common scenario in financial calculations, such as applying sales tax to product prices.

Main.java

Main.java

1234567891011121314151617
package com.example; import java.util.List; import java.util.Arrays; public class Main { public static void main(String[] args) { List<Double> prices = Arrays.asList(100.0, 200.0, 50.0); // Apply a 10% tax to each price List<Double> finalPrices = prices.stream() .map(price -> price * 1.1) .toList(); System.out.println(finalPrices); } }
Note
Note

You will learn to use terminal operations in the next section, so in this example, you used a basic terminal operation, toList(), which converts the stream into a List.

In this example, each price in the list is increased by 10% using the map() method.

You multiply each value by 1.1 to account for the tax and collect the results into a new list. This transformed list can then be used for further calculations, such as generating invoices or financial reports.

Primitive Type

Note
Definition

Stream API provides specialized primitive streams: IntStream, LongStream, and DoubleStream. These allow direct operations on numbers without wrapping them in objects like Integer, Long, or Double.

Unlike the regular map method, which returns a stream of objects, mapToInt(), mapToLong(), and mapToDouble() return streams of primitive types, reducing memory overhead and improving performance.

Practical Example

The following example converts a list of numeric strings into primitive streams and prints the values.

Main.java

Main.java

1234567891011121314151617181920212223242526272829303132
package com.example; import java.util.List; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.DoubleStream; public class Main { public static void main(String[] args) { List<String> numbers = List.of("10", "20", "30", "40"); // Convert to `IntStream` IntStream intStream = numbers.stream() .mapToInt(Integer::parseInt); System.out.print("IntStream: "); intStream.forEach(n -> System.out.print(n + " ")); System.out.println(); // Convert to `LongStream` LongStream longStream = numbers.stream() .mapToLong(Long::parseLong); System.out.print("LongStream: "); longStream.forEach(n -> System.out.print(n + " ")); System.out.println(); // Convert to `DoubleStream` DoubleStream doubleStream = numbers.stream() .mapToDouble(Double::parseDouble); System.out.print("DoubleStream: "); doubleStream.forEach(n -> System.out.print(n + " ")); } }

This example processes a list of numeric strings.

First, mapToInt() converts the values into an IntStream, printing each number as an integer. Next, mapToLong() creates a LongStream, maintaining the same numerical values but in the long type. Finally, mapToDouble() transforms the data into a DoubleStream, converting the integers into decimal numbers.

Using primitive streams ensures efficient handling of numerical data while avoiding unnecessary object creation.

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 1
some-alt