This post will discuss how to build a Map from a List of keys and values in Java.

1. Java 8

Since Java 8, you can do this in a single line using Stream API. Since a stream is a sequence of elements and not a sequence of key-value pairs, you can’t directly construct a map out of it. You need to specify how to extract keys and values from elements of the stream using the Collectors.toMap() method.

Download  Run Code

Output:

{0=1, 1=2, 2=3, 3=4}

 
The code will throw IllegalStateException on encountering a duplicate key. We can provide a merge function to resolve collisions between values associated with the same key, as shown below:

Download  Run Code

Output:

{0=1, 1=2, 2=3}

2. Using for loop

Here’s a version without streams (works with Java 8 and above). You can easily modify the code to handle duplicate keys.

Download  Run Code

Output:

{0=1, 1=2, 2=3, 3=4}

That’s all about building a Map from a List of keys and values in Java.