DEV Community

Cover image for What is `map` in a Java Stream
Gunnar Gissel
Gunnar Gissel

Posted on • Edited on • Originally published at gunnargissel.com

9 2

What is `map` in a Java Stream

Originally published at www.gunnargissel.com

Mapping is how to convert one type of object to another with a stream. Say you have a set of Fruit and you want to show people what is in your set. It would be helpful to have a list of fruit names to do so.

fruitList.stream().map(fruit::getName).collect(Collectors.toList);
Enter fullscreen mode Exit fullscreen mode

That's pretty simple; you can imagine how to do that in real life with a basket of fruit.

Pick up a piece of fruit, write its name down. Pick up another piece of fruit, write its name down, etc.

Mapping also lets you you can't easily simulate in real life. Say you have a Fruit set and you want Oranges, instead of Apples (I think this is closer to transmutation than swapping, but it's a metaphor, ymmv).

You can do that, with Java:

fruitList.stream().map(fruit -> {
    if( fruit instanceof Apple){
        return new Orange();
    }
    return  fruit;
}).collect(Collectors.toSet);
Enter fullscreen mode Exit fullscreen mode

If you liked this article, sign up for my mailing list to get monthly updates on interesting programming articles

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (2)

Collapse
 
mbtts profile image
mbtts

Good article and thank you for sharing.

For those not aware it is also possible to use a method reference for the first example:

fruitList.stream()
         .map(Fruit::getName)
         .collect(toList());

This is just a more succinct syntax for invoking the #getName method on each and every instance of Fruit in the stream. As such even though it may appear to be invoked on the class it is not a static method.

Also a small API thing - it is Collectors#toList not #asList (and #toSet).

Collapse
 
andrekelvin profile image
AndreKelvin

Thanks. I now fully understand this mapping thing

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay