Java 8 Streams - Creating a Map from a Collection, List, or Set

In this tutorial I want to show you how to convert lists or sets into a map with the Java 8 Streaming API Collection.
Java 8

Java 8 Streams – Create a map from a collection, list or set

Preamble

With the introduction of streams in Java 8 the writing of Java code has changed. With Java 8 you can now transfer objects from a list to a map in a comfortable way. How to implement this I will show you in this tutorial.

Requirement

  • Java knowledge

Convert Collection, List or Set to Map with the Java 8 Streaming API

As a developer you sometimes face the problem that objects of a collection, list or set have to be transferred into a map. There are different reasons for this. One reason might be that the access to the elements of a map is much faster than the access to the elements of a list. In this case it makes sense to transfer the collection, list or set into a map in advance.

In this tutorial we assume that we have a list of the class Customer.java and that it has the properties id, firstname, lastname.

With the Streamin API of Java 8 we can use streams and at the end of the processing we can transfer them via collectors into a target structure suitable for us. In this example we want to convert from a list to a map.

The following code shows how to transfer a List<Customer> to Map<String, Customer>.

The Result

We have now learned how to convert lists or sets into a map with Java 8 and Streams Collection. With the collector classes it is also possible to convert the list into a set or to convert the objects in the list into another class. The Streams API offers a lot of possibilities. How to convert the objects of a list into another class you can see in my next tutorial Java 8 Stream Object mapping.

I hope you enjoyed my little tutorial. If you should have questions, criticism or suggestions, then I would be pleased, if you would leave a comment.

Verwandte Beiträge

Leave a comment

Diese Website verwendet Cookies. Durch die Nutzung unserer Services erklären Sie sich damit einverstanden, dass wir Cookies setzen. weitere Informationen

Diese Website verwendet Cookies. Durch die Nutzung unserer Services erklären Sie sich damit einverstanden, dass wir Cookies setzen.

Schließen