A logo showing the text blog.marcnuri.com
Español
Home»Java»Java 8 Streams: Convert List into Map

Recent Posts

  • Fabric8 Kubernetes Client 7.2 is now available!
  • Connecting to an MCP Server from JavaScript using AI SDK
  • Connecting to an MCP Server from JavaScript using LangChain.js
  • The Future of Developer Tools: Adapting to Machine-Based Developers
  • Connecting to a Model Context Protocol (MCP) Server from Java using LangChain4j

Categories

  • Artificial Intelligence
  • Front-end
  • Go
  • Industry and business
  • Java
  • JavaScript
  • Legacy
  • Operations
  • Personal
  • Pet projects
  • Tools

Archives

  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • August 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
  • February 2020
  • January 2020
  • December 2019
  • October 2019
  • September 2019
  • July 2019
  • March 2019
  • November 2018
  • July 2018
  • June 2018
  • May 2018
  • April 2018
  • March 2018
  • February 2018
  • December 2017
  • July 2017
  • January 2017
  • December 2015
  • November 2015
  • December 2014
  • March 2014
  • February 2011
  • November 2008
  • June 2008
  • May 2008
  • April 2008
  • January 2008
  • November 2007
  • September 2007
  • August 2007
  • July 2007
  • June 2007
  • May 2007
  • April 2007
  • March 2007

Java 8 Streams: Convert List into Map

2018-03-30 in Java tagged Collector / Java / Java 8 / List / Map / Streams by Marc Nuri | Last updated: 2021-03-20
Versión en Español

Introduction

In this post we’ll see how to use Java Streams introduced in Java 8 to obtain a Map from a List.

Maps are data structures composed of a collection of key-value elements such that a key is unique within the collection. This allows us to perform searches to find an element with a given key really quickly, without the need to iterate through the full collection.

It’s a really common situation that when we have to solve a problem where the start point is a list of elements, we need to convert this list to a map so that we can optimize the performance of the algorithm for the solution. It is at these times when Java 8 Streams allow us to perform this conversion in a simple and elegant way.

In this post we’ll see how to convert a list of Github repositories into a map. We start with the class GithubRepo:

1/** ... **/
2public class GithubRepo {
3  private String name;
4  @JsonProperty("full_name")
5  private String fullName;
6  private String description;
7  private Boolean fork;
8  @JsonIgnore
9  private Integer localVersion;
10  /** ... **/
11}

List to Map with no duplicate keys

If we are really sure that the List we want to convert into a Map contains no duplicate elements, we can use the following code:

1repos.stream().collect(Collectors.toMap(GithubRepo::getName, Function.identity()));

The first step is to convert the list into a Stream and then, without any transformation, collect the results using one of the default Java 8 Collectors.

For the Map key we are going to use the name of the repository in this case we are using the code GithubRepo::getName which is the recommended equivalent for the expression gr -> gr.getName(). As the Map value we want to use the same element from the list, for this purpose Java offers out of the box Function.identity() which is the recommended equivalent for the expression gr -> gr.

As already stated, one of the requirements for this Collector is that there are no duplicate keys within the initial list. In case a duplicate key is received, an IllegalStateException will be thrown as you can see in this test listToMap_duplicatesList_shouldThrowException.

List to Map with duplicate keys

If we are not sure or we simply don’t know if the original list contains duplicities we’ll use another Collector that can manage merging for these duplicities. For this sake, the method we used earlier admits a third parameter as a lambda expression that will be in charge of merging the elements for a given duplicate key.

1repos.stream().collect(Collectors.toMap(GithubRepo::getName, Function.identity(),
2  (ghrPrevious, ghrNew) -> ghrNew));

The example shows an anonymous function as the third parameter for the toMap collector. This function has 2 initial parameters ghrPrevious and ghrNew and must return a single element of the same type. In this case we are returning the newer element (ghrNew) but you could return the previous or a transformation of either of them or a new one.

List to Map keeping key ordering

Collectors.toMap admits a fourth parameter to specify the constructor of the Map that the method returns.

1repos.stream().collect(Collectors.toMap(GithubRepo::getName, Function.identity(),
2        (ghrPrevious, ghrNew) -> ghrNew, TreeMap::new));

In this case we want to obtain an instance of TreeMap which implements the SortedMap interface. This Map is sorted by the natural ordering of its keys or by the comparator provided at the constructor argument.

In the previous example the map will sorted alphabetically by the order of its keys. In the next example the map will be sorted by reverse order of its keys as it’s using Comparator.reverseOrder() as the TreeMap constructor argument:

1repos.stream().collect(Collectors.toMap(GithubRepo::getName, Function.identity(),
2        (ghrPrevious, ghrNew) -> ghrNew,
3        () -> new TreeMap(Comparator.reverseOrder())));

Conclusion

This post shows how to convert in a simple and elegant way a List data structure to a Map data structure using Java 8 streams and the method Collectors.toMap.

You can find the full source code for this article at GitHub.

Java 8 Streams
Java 8 Streams
Twitter iconFacebook iconLinkedIn iconPinterest iconEmail icon

Post navigation
Java 10: Testing the new releaseSpring Data MongoDB: Custom repository implementation
© 2007 - 2025 Marc Nuri