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 studentMap = (Map) studentList.stream()
.collect(Collectors.toMap(Student::getStudentId, Function.identity()));
//Step 4: Let's print the results
for (Map.Entry 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)
More Posts related to Java,
- How to install Java 11 on Mac
- Get Client IP address from HTTP Response in Java
- SharePoint Open in the client application document opens in browser
- How to verify if java is installed on the computer and get version detail
- Java - Check if array contains the value
- Your JBoss Application Server 7 is running However you have not yet added any users to be able to access the admin console
- How to run Java Unit Test cases with Apache Maven?
- What Java version is used for Minecraft 1.18
- List of jar files for Jax-ws (SOAP) based Java Web Services
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- Convert Instant timestamp into LocalDateTime Java Code Example
- Java - Calculate time taken for the code to execute in milliseconds or nanoseconds
- Create simple struts2 project using maven commands
- Java - PatternSyntaxException
- List of Online Java compiler with console
- Minecraft Java Edition
- How to declare and initialize Array in Java Programming
- [Solved] com.sun.xml.ws.transport.http.servlet.WSServletContextListener ClassNotFoundException
- Java XML-RPC 3.1.x based web service example
- Simple Struts 2 Tutorial in eclipse with tomcat 7 server
- Java 8 foreach loop code examples
- Java -Day of the week using Java 8 DayOfWeek Enum
- Java 8 - Convert List to Map Examples
- Java: TimeZone List with GMT/UTC Offset
- list of jars required for hibernate 4.x.x
More Posts:
- Safari appends .html extension to files that are downloaded - Mac-OS-X
- SQLite with Android Easy to Understand Tutorial that covers Select, Insert, Update and Delete - Android
- How to Search Something (string) in Android Studio Project like Eclipse - Android-Studio
- SharePoint workflow Canceled - Coercion Failed: Unable to transform the input lookup data into the requested type - SharePoint
- How to take user input from the console in a Python program - Python