How to Convert List to Map using Java 8

By | June 23, 2020

In this post, we will learn How to convert List to Map using Java 8 Stream API, where a key is any attribute from the object and value is the object itself or any attribute from Object.

Let’s clarify it using the below example.

Employee.java

StreamApiExample.java

Output of this program:

——-Getting Map from List where key = id, value = name in Map using Stream API———-
empIdAndNameMap : {1072=Marry, 1112=Raj, 1992=Sofiya, 1882=Sam, 1002=Sean, 1772=Hema}
empIdAndNameMap2 : {1072=Marry, 1112=Raj, 1992=Sofiya, 1882=Sam, 1002=Sean, 1772=Hema}
——-Getting Map from List where key = id, value = salary in Map using Stream API———-
empNameAndSalaryMap : {Hema=9000.0, Sean=10000.0, Sofiya=3000.0, Raj=16000.0, Sam=30000.0, Marry=15000.0}
——-Getting Map from List where key = id, value = Employee Object in Map using Stream API———-
{1072=Employee [id=1072, name=Marry, isFemale=true, isMale=false, salary=15000.0], 1112=Employee [id=1112, name=Raj, isFemale=false, isMale=true, salary=16000.0], 1992=Employee [id=1992, name=Sofiya, isFemale=true, isMale=false, salary=3000.0], 1882=Employee [id=1882, name=Sam, isFemale=false, isMale=true, salary=30000.0], 1002=Employee [id=1002, name=Sean, isFemale=false, isMale=true, salary=10000.0], 1772=Employee [id=1772, name=Hema, isFemale=true, isMale=false, salary=9000.0]}

 

You May Also Like:

Explain Stream API introduced in Java 8 ?
There is a stream of words which contains Anagrams. How would you print anagrams in a single bucket from that stream?
Java Spliterator Example
Differences Between map() And flatMap() in Java 8 ?
What are the new features added in Java 8?

That’s all in this post of  How to convert List to Map using Java
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *