Home > Java > javaTutorial > What is the difference between forEach and map in streams?

What is the difference between forEach and map in streams?

Barbara Streisand
Release: 2024-11-19 16:55:03
Original
928 people have browsed it

What is the difference between forEach and map in streams?

forEach: A terminal operation that performs an action on each element of the stream but does not transform or return data.

map: An intermediate operation that transforms each element in the stream and returns a new stream of transformed elements.

Basic forEach with List

import java.util.Arrays;
import java.util.List;

public class ForEachExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

        // Print each name using forEach
        names.forEach(name -> System.out.println(name));
    }
}

Copy after login

map example

List<String> names = Arrays.asList("Alice", "Bob");
names.stream().forEach(System.out::println); // Simply prints each name

List<Integer> nameLengths = names.stream()
                                 .map(String::length) // Transforms each name to its length
                                 .collect(Collectors.toList());

Copy after login

The above is the detailed content of What is the difference between forEach and map in streams?. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template