0

Java 8 Convert Stream values to Map

This post demonstrates how to convert a stream of objects to a Map object using Collectors.toMap(…) methods.

Our JavaBean

Our Demo Application

Example 1

Using Collectors.toMap method with 2 parameters

This outputs the following

Example 2

Using Collectors.toMap method with 3 parameters. For this example, we need two NewPersonBean object with the same ids to trigger the use of the 3rd parameter to “handle collisions”.

This outputs the following

Example 3

Using Collectors.toMap method with 4 parameters.

This outputs the following

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert