GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Java Stream map - map operations on Java streams Java Stream maplast modified May 25, 2025 In this article, we explore how to effectively perform map operations on Java streams, leveraging functional programming principles to transform data efficiently. A Java Stream is a sequence of elements originating from a data source that supports aggregate operations. Streams do not store elements—instead, they compute results on demand, making them particularly useful for handling large datasets. Elements can be consumed from sources such as collections, arrays, or I/O resources, allowing developers to process data dynamically. Stream aggregate operations function similarly to SQL queries, enabling developers to perform filtering, mapping, reducing, matching, searching, and sorting directly on the data stream. By leveraging stream chaining, multiple operations can be applied sequentially, enhancing code readability and efficiency. Unlike traditional collections that rely on external iteration, streams are designed to use internal iteration, optimizing execution control and performance. Stream Map Operation
The
The
The benefits of using the map method include:
The map method is a powerful tool for applying transformations to data within Java streams, making it essential for functional programming and modern Java development. Mapping an arithmetic operationIn the first example, we map an arithmetic operation on a sequence of values. Main.java
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 Converting Strings to UsersThe next example demonstrates how to convert a stream of strings into a stream of custom objects. Main.java
void main() throws IOException {
String data = """
John,Doe
Jane,Smith
Alice,Johnson
Bob,Brown
""";
var users = data.lines()
.map(line -> line.split(",", 2))
.map(fields -> new User(fields[0].trim(), fields[1].trim()))
.toList();
System.out.println(users);
}
record User(String firstName, String lastName) {
}
We create a The mapToInt method
The Main.java
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
int sumEvenNumbers = numbers.stream()
.mapToInt(Integer::intValue) // Convert Integer objects to primitive int
.filter(n -> n % 2 == 0) // Keep only even numbers
.sum(); // Compute sum
System.out.println("Sum of even numbers: " + sumEvenNumbers);
The example demonstrates how to use the Mapping a custom methodIn the next example we map a custom method on a stream of strings. Main.java
void main() {
var words = Stream.of("cardinal", "pen", "coin", "globe");
words.map(this::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 fileWe can read values from a CSV file into a list using map methods. numbers.csv
2,3,5,6,1,0 9,5,6,3,2,1
We have these values in the Main.java
void main() throws IOException {
int sum = Files.lines(Path.of("numbers.csv")) // Stream file lines directly
.mapToInt(line -> Arrays.stream(line.split(","))
.mapToInt(Integer::parseInt)
.sum()) // Convert and sum each line
.sum(); // Total sum
System.out.println("Total sum: " + sum);
}
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 int sum = Files.lines(Path.of("numbers.csv")) // Stream file lines directly
.mapToInt(line -> Arrays.stream(line.split(","))
.mapToInt(Integer::parseInt)
.sum()) // Convert and sum each line
We create a stream from the file lines. Each line is split by commas, and each
resulting string is converted to an integer using
$ java Main.java [2, 3, 5, 6, 1, 0, 9, 5, 6, 3, 2, 1] Extracting specific attributes
The Main.java
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().toList();
System.out.println(userNames);
var occupations = users.stream().map(User::occupation)
.sorted(Comparator.reverseOrder()).distinct().toList();
System.out.println(occupations);
}
record User(String name, String occupation) {
}
In this example, we have a list of $ java Main.java [Jane, Jane, Milan, Peter, Robert] [teacher, programmer, designer, accountant] SourceIn this article we have worked with Java Stream mapping operations. AuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Java tutorials. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |