Core Java

Java streams api – Convert list to map

Hello. In this tutorial, we will understand how to convert a list to a map, using the java streams api collect(Collectors.toMap(…)) method.

1. Introduction

Collectors.toMap(…) method returns a new instance of the map with keys as per keyMapper function and values as per the valueMap function. It is represented by the following semantics syntax –

Implementation class

<T,K,U> Collector<T,?,Map<K,U>> toMap(
                                  Function<? super T,? extends K> keyMapper,
                                  Function<? super T,? extends U> valueMapper)

In some cases the toMap(…) can also take the mergeFunction and mapSupplier as input arguments to resolve collisions between values associated with the same key and a function that provides a new instance of the desired implementation of the map respectively.

2. Practice

Let us dive into some practice stuff from here and I am assuming that you already have Java 1.8 or greater installed on your local machine. I am using JetBrains IntelliJ IDEA as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Creating an implementation class

Create a java file that will show the implementation of the Collectors.toMap(…) method. We have used a static block to populate the person list which we’ll use to perform the list-to-map conversion with different keys and values. You’re free to change the example as your wish.

Implementation class

package com.learning;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

class Person {

  private final int id;
  private final String name;

  public Person(int id, String name) {
    this.id = id;
    this.name = name;
  }

  public int getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  @Override
  public String toString() {
    return "Id= " + getId() + ", Name= " + getName();
  }
}


public class JavaStreamApiListToMap {

  public final static List<Person> persons = new ArrayList<>();

  static {
    for (int i = 0; i < 10; i++) {
      persons.add(new Person(i + 1, "Alpha-" + i + 1));
    }
  }

  public static void main(String[] args) {
    // convert object list to int, object map
    Map<Integer, Person> personMap = convertToMap();
    personMap.forEach(
        (key, value) -> System.out.println("id= " + key + " :: person[" + value.toString() + "]"));
    
    System.out.println("\n");

    // convert object list to int, string map
    Map<Integer, String> personMap1 = convertToMap1();
    personMap1.forEach((key, value) -> System.out.println("id= " + key + " :: value= " + value));
  }

  // method1
  private static Map<Integer, Person> convertToMap() {
    return persons.stream().collect(Collectors.toMap(Person::getId, Function.identity()));
  }

  // method2
  private static Map<Integer, String> convertToMap1() {
    return persons.stream().collect(Collectors.toMap(Person::getId, Person::getName));
  }
}

3. Demo

Run the file as a java file and if everything goes well the following logs will be shown on the IDE console.

Fig. 1: Console output

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

4. Summary

In this tutorial, we discussed the practical implementation of Collectors.toMap(…) method with the help of various examples.

to find the longest substring without repeating characters. You can download the source code from the Downloads section.

5. Download the Project

This was a tutorial to understand the practical implementation Collectors.toMap(…) method.

Download
You can download the full source code of this example here: Java streams api – Convert list to map

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button