Java Stream map
last modified July 8, 2024
In this article we show how to perform map operations on Java streams.
Java Stream is a sequence of elements from a source that supports aggregate operations. Streams do not store elements; the elements are computed on demand. Elements are consumed from data sources such as collections, arrays, or I/O resources.
Stream aggregate operations are similar to SQL operations. We can apply filtering, mapping, reducing, matching, searching, or sorting operations on streams. Streams allow chaining of multiple stream operations. Unlike collections which use external iterations, streams are iterated internally.
Stream map
We can change stream elements into a new stream; the original source is not
modified. The map
method returns a stream consisting of the results
of applying the given function to the elements of a stream. The
map
is an itermediate operation.
Mapping an arithmetic operation
In the first example, we map an arithmetic operation on a list of values.
import java.util.Arrays; import java.util.stream.IntStream; void main() { var nums = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8); var squares = nums.map(e -> e * e).toArray(); System.out.println(Arrays.toString(squares)); }
In the example, we create a stream of integers. With the map
method we apply an arithmetic operation on the values and then transform
them into an array.
The map/mapToInt methods
In the following example we use map
and mapToInt
methods in one stream.
import java.util.Random; import java.util.stream.Stream; void main() { Stream.generate(new Random()::nextDouble) .map(e -> (e * 100)) .mapToInt(Double::intValue) .limit(5) .forEach(System.out::println); }
The example generates five random double values. Using the mapping methods, each of the randomly generated values is multiplied by 100 and transformed into integer.
Mapping a custom method
In the next example we map a custom method on a stream of strings.
import java.util.stream.Stream; void main() { var words = Stream.of("cardinal", "pen", "coin", "globe"); words.map(JavaStreamMapEx3::capitalize).forEach(System.out::println); } String capitalize(String word) { word = word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase(); return word; }
The example capitalizes each of the words in the stream.
Reading from CSV file
We can read values from a CSV file into a list using map methods.
2,3,5,6,1,0 9,5,6,3,2,1
We have these values in the numbers.csv
file.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collection; import java.util.stream.Collectors; void main() throws IOException { var lines = Files.readAllLines(Path.of("src/main/resources/numbers.csv")); var vals = lines.stream().map(line-> Arrays.asList(line.split(","))) .flatMap(Collection::stream).mapToInt(Integer::valueOf) .boxed().collect(Collectors.toList()); System.out.println(vals); }
First, we read the CSV file into a list of strings. Then we create a stream from the list and apply mapping methods to get a list of integers in the end.
var lines = Files.readAllLines(Path.of("src/resources/numbers.csv"));
With Files.readAllLines
, we read all lines of the file into a list
of strings.
var vals = lines.stream().map(line-> Arrays.asList(line.split(","))) .flatMap(Collection::stream).mapToInt(Integer::valueOf) .boxed().collect(Collectors.toList());
We create a stream from the list, split the strings into an list of string numbers. The list is flattened, transformed into integers and collected into the final list.
[2, 3, 5, 6, 1, 0, 9, 5, 6, 3, 2, 1]
Map with a list of user objects
In the next example we use map operations on a list of user objects.
import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; void main() { var users = List.of(new User("Peter", "programmer"), new User("Jane", "accountant"), new User("Robert", "teacher"), new User("Milan", "programmer"), new User("Jane", "designer")); var userNames = users.stream().map(User::name).sorted() .collect(Collectors.toList()); System.out.println(userNames); var occupations = users.stream().map(User::occupation) .sorted(Comparator.reverseOrder()).distinct() .collect(Collectors.toList()); System.out.println(occupations); } record User(String name, String occupation) { }
The example creates a list of sorted names from a list of users and a list of unique occupations in a reverse order.
Source
In this article we have have worked with Java Stream mapping operations.
Author
List all Java tutorials.