Java, Software Development

Java 8 Convert Stream Values to Map Entries Examples

This post shows how to convert a stream of objects to Map entries in Java using Collectors.toMap methods. Furthermore, we’ll handle duplicate IDs for May keys. Most importantly. We need Java 8 for this post because the Stream API is only available in this version.

The Class for Our Map Object

Consider the following codes. We will use the class to create a list of objects and convert them into Map entries. Since Map entries are key-value pairs, we need to use id as key and an instance of NewPersonBean as value.

Notice that we have a List object within the class. We will use the list to gather duplicate (handle collisions) entries from Java Stream values.

Convert Java Stream Values to Map Entries

Here the example codes that show how we convert Java Stream values to Map entries.

Example 1 – Using Two Parameters

The first example uses Collectors.toMap method with two parameters.

The codes generate the following output.

Example 2 – Handle Collisions

This example uses a Collectors.toMap method with three parameters. Therefore, we need two NewPersonBean objects with identical ids to trigger the 3rd parameter to “handle collisions.”

The codes generate the following output.

Example 3 – Handle Collision And Accumulate Duplicates

The following example uses Collectors.toMap method with four parameters. The difference between this example and the previous example is we accumulate the duplicates we find during the conversion.

 

The sample codes output the following result.

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like