DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert Files to Thumbnail Images in Java
  • Understanding Floating-Point Precision Issues in Java
  • How To Convert Common Documents to PNG Image Arrays in Java
  • How To Convert ODF Files to PDF in Java

Trending

  • Doris: Unifying SQL Dialects for a Seamless Data Query Ecosystem
  • *You* Can Shape Trend Reports: Join DZone's Software Supply Chain Security Research
  • Zero Trust for AWS NLBs: Why It Matters and How to Do It
  • My LLM Journey as a Software Engineer Exploring a New Domain
  1. DZone
  2. Coding
  3. Java
  4. How to Convert List to Map in Java

How to Convert List to Map in Java

Want to learn how to convert list to map in Java? Click here to learn how to do this in both Java 7 and Java 8.

By 
Hussein Terek user avatar
Hussein Terek
·
Updated Jul. 23, 18 · Tutorial
Likes (26)
Comment
Save
Tweet
Share
129.6K Views

Join the DZone community and get the full member experience.

Join For Free

This tutorial shows the different ways to convert a List to Map in Java.

Java 7 and Before

With Java 7 and older releases, the only way to convert a List  to Map  is to iterate over the list and populate the map manually.

In the following example, we implement a utility method that accepts a list of Student objects and populates out of it a  HashMap  with id  as a key and name  as a value.

public static Map<Integer,String> listToHashmapJava7Below(List<Student> students)
{
    Map<Integer, String> studentsMap = new HashMap<Integer, String>();

    for(Student student : students)
    {
        studentsMap.put(student.getId(), student.getName());
    }

    return studentsMap;
}


Java 8

With Java 8, you can convert a List  to Map  in one line using the  stream()  and  Collectors.toMap() utility methods.

public static Map<Integer,String> listToHashmapJava8(List<Student> students)
{
    Map<Integer, String> studentsMap = students.stream().collect(Collectors.toMap(Student :: getId, Student :: getName));
    return studentsMap;
}


 The Collectors.toMap() method collects a stream as a Mapand uses its arguments to decide what key/value to use.

Java 8: Handle Duplicate Keys

 The Collectors.toMap() fails when converting a list with duplicate items.

In order to handle duplicates, you can pass a third argument that informs the  toMap()  which value to consider when facing duplicate items.

In the following example, we decide to consider the old value or, in other words, to keep the existing value without updating each time the map faces a duplicate:

public static Map<Integer,String> listToHashmapJava8WithDuplicates(List<Student> students)
{
    Map<Integer, String> studentsMap = students.stream().collect(Collectors.toMap(Student :: getId, Student :: getName
                                           , (oldValue, newValue) -> oldValue));
    return studentsMap;
}


If you want to override the existing value on duplicates, use  (oldValue, newValue) -> newValue .

Java 8: Preserve List Order

In order to preserve the order of the list items inside the  Map , you can pass another parameter to  Collectors.toMap()  which decides what type of map to use.  LinkedHashMap  is well known in preserving the order of its entries.

public static Map<Integer,String> listToHashmapJava8PreserveOrder(List<Student> students)
{
    Map<Integer, String> studentsMap = students.stream().collect(Collectors.toMap(Student :: getId, Student :: getName
                                           , (oldValue, newValue) -> oldValue,LinkedHashMap::new));
    return studentsMap;
}



If you enjoyed this article and want to learn more about Java Collections, check out this collection of tutorials and articles on all things Java Collections.

Java (programming language) Convert (command)

Published at DZone with permission of Hussein Terek, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert Files to Thumbnail Images in Java
  • Understanding Floating-Point Precision Issues in Java
  • How To Convert Common Documents to PNG Image Arrays in Java
  • How To Convert ODF Files to PDF in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!