DEV Community

realNameHidden
realNameHidden

Posted on • Edited on

5 1 1 1 1

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));
    }
}

Enter fullscreen mode Exit fullscreen mode

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());

Enter fullscreen mode Exit fullscreen mode

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay