Java 8 map method example

Java 8 map method Examples

In Java 8 streams map() method is one of the most important and the widely used methods of streams. In this tutorial, we would be looking at various ways we can use map method. These examples can help you understand the usage of Java 8 stream map() method. The javadocs describes the example:() method as:

Returns a stream consisting of the results of applying the given function to the elements of this stream.

Examples of map method

1. Convert a list of Strings to a list of Integers

The map() method provides a way to convert an input object to a different/same output object. Here we will transform a simple list of numbers as strings to a list of Integers.

2. Change the case of Strings

We looked at converting the type of object above. Now we will do an operation on the items in a list and create a new list. A simple example that changes the case of the Strings of the list.

3. Mixing Map with filter

You can use map() method with other useful functions provided by Java 8 stream framework. In the below example, we would filter all the students that have percentage higher than 75%. And then get the names of these students and print them.

4. An interesting example : Map And create a phrase with it

Let’s make the above example a little bit more interesting and create a sentence out of the names we received in the above example.

 Summary

We looked at some interesting ways we can use the map method. I hope that usage of map() method is more clear to you after reading and practicing the above examples. In case you have some more interesting examples, please share in comments.

Leave a Reply