Java Stream map
last modified January 27, 2024
Java Stream map tutorial shows how to perform map operations on Java streams.
Java Stream
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.
Java 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.
Java Stream map example
In the first example, we map an arithmetic operation on a list of values.
package com.zetcode; import java.util.Arrays; import java.util.stream.IntStream; public class JavaStreamMapEx { public static void main(String[] args) { 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.
[1, 4, 9, 16, 25, 36, 49, 64]
Java Stream map example II
In the following example, we use map
and mapToInt
methods in one stream.
package com.zetcode; import java.util.Random; import java.util.stream.Stream; public class JavaStreamMapEx2 { public static void main(String[] args) { 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.
66 25 18 35 47
Java Stream map example III
In the next example, we map a custom method on a stream of strings.
package com.zetcode; import java.util.stream.Stream; public class JavaStreamMapEx3 { public static void main(String[] args) { var words = Stream.of("cardinal", "pen", "coin", "globe"); words.map(JavaStreamMapEx3::capitalize).forEach(System.out::println); } private static 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.
Cardinal Pen Coin Globe
Java Stream map example IV
In the next example, we 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.
package com.zetcode; 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; public class JavaStreamMapEx4 { public static void main(String[] args) throws IOException { var lines = Files.readAllLines(Path.of("src/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]
Java Stream map example V
In the next example, we use map operations on a list of user objects.
package com.zetcode; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class JavaStreamMapEx5 { public static void main(String[] args) { 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.
[Jane, Jane, Milan, Peter, Robert] [teacher, programmer, designer, accountant]
Source
In this article we have have worked with Java Stream mapping operations.
Author
List all Java tutorials.