In this tutorial we will take a look at how to convert a Java Collection List to a Map, there are multiple ways in which you can do so, we will take a look at using Streams,
Example: Student.javaLet us first create our Class called Student,
public class Student {
int studentId;
String studentName;
int studentAge;
public Student(int studentId, String studentName, int studentAge) {
this.studentId = studentId;
this.studentName = studentName;
this.studentAge = studentAge;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}
@Override
public String toString() {
return "Student{" +
"studentId=" + studentId +
", studentName='" + studentName + '\'' +
", studentAge=" + studentAge +
'}';
}
}
ListToMapExample.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Java 8 Example to Convert a
* Collection List Object into
* a Map
*
* Author: Code2care.org
* Date: 03-Apr-2022
* Version: 1.0
*
*/
public class ListToMapExample {
public static void main(String[] args) {
//Step 1: Create some Student Objects
Student student1 = new Student(1, "Sam", 19);
Student student2 = new Student(2, "Mike", 18);
Student student3 = new Student(3, "Alex", 21);
//Step 2: Add them to a List
List studentList = new ArrayList<>();
studentList.add(student1);
studentList.add(student2);
studentList.add(student3);
//Step 3: Converting Student List to a Map using Stream
Map<Integer, Student> studentMap = (Map<Integer, Student>) studentList.stream()
.collect(Collectors.toMap(Student::getStudentId, Function.identity()));
//Step 4: Let's print the results
for (Map.Entry<Integer, Student> entry : studentMap.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}

Java 8 - Convert List to Map Example Output
Note that the key that you identify from the List for the Map should be unique or else you will get java.lang.IllegalStateException: Duplicate key
Exception in thread "main" java.lang.IllegalStateException: Duplicate key 2 (attempted merging values Student{studentId=2, studentName='Mike', studentAge=18} and Student{studentId=2, studentName='Mike', studentAge=18})
at java.base/java.util.stream.Collectors.duplicateKeyException(Collectors.java:133)
at java.base/java.util.stream.Collectors.lambda$uniqKeysMapAccumulator$1(Collectors.java:180)
at java.base/java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
at ListToMapExample.main(ListToMapExample.java:35)
-
Have Questions? Post them here!
More Posts related to Java,
- Add two numbers using Java Generics
- Convert Java List to Json String using Jackson
- Convert Java Object to JSON using Jackson Library
- Java SE JDBC: Insert with PreparedStatement Example
- [Program] How to read three different values using Scanner in Java
- Java JDBC Batch Update Example with PreparedStatement
- Java Stream flatmap() Examples
- Save Java Object as JSON file using Jackson Library
- Java get day of the week as an int using DayOfWeek
- Create Nested Directories using Java Code
- Java JDBC Delete a Record in Database Table using PreparedStatement
- List of jars required for Struts2 project
- Convert Java Object to XML using Jackson Library
- Struts2 : java.lang.ClassNotFoundException: org.apache.commons.fileupload.RequestContext
- Java JDBC Get Id of the Inserted Record with AutoIncrement
- How to list all tables using Java JDBC
- Java Jackson ObjectMapper Class with Examples
- Fix: Maven - Failed to execute goal - Compilation failure - Source/Target option 5 is no longer supported. Use 7 or later
- Eclipse : The type java.lang.CharSequence cannot be resolved. Indirectly referenced from required .class files
- Formatting Double in Java [Examples]
- How to run Java Unit Test cases with Apache Maven?
- [fix] NullPointerException Cannot Invoke findById because Repository is null - Java Spring
- [Fix] java: integer number too large compilation error
- [Java] Read a File with UTF-8 Encoding
- How to detect Operating System using Java code
More Posts:
- Facebook : Warning: Request without access token missing application ID or client token - Facebook
- Java Jackson ObjectMapper Class with Examples - Java
- Eclipse : Workspace was written with an older version of the product and will be updated - Eclipse
- Disabling Spell Check in Android Studio - Android-Studio
- zsh: command not found: cls macOS Big Sur - MacOS
- Unbound classpath container: JRE System Library [JavaSE-1.7] - Java
- How to install Python Specific version (3.8, 3.9 or 3.10) using Brew - Python
- Make Android TextView Clickable like Buttons - Android