Java 8 Stream map example

In this tutorial we will show you how to use the new Java 8 stream map method. This allows you to conveniently convert an object from one type to another.

Simple Java 8 stream map example:

The example below is a simple showcase of how to use the map function to convert a list of strings to a list of integers.

Running the above code produces the following output.

Complex Java 8 stream map example:

Below is an example of showing how to convert a list of objects to another object type.

 

As you can see from the example above, you can use the map function to convert each element in the privateUsers list to a another object PublicUser in this case. The collect() function allows you to collect the new objects into a new list.

Running the above code produces the following output.

In conclusion, I hope you found this post useful. I hope this has given you a better understanding on how to use the map method for your project.

Similar posts:

  1. Java 8 forEach examples
  2. Java 8 Stream flatmap example
  3. Java 8 Comparator examples
  4. Convert Java object to JSON using GSON
  5. How to write to a file in Java

References:

  1. Java Streams API Documentation

Leave a Reply