Java Stream List to Map

Java Stream List to Map

In this post, we will see how to convert List to Map using Stream in java 8.

Collectors’s toMap() can be used with stream to convert List to Map in java.

Consider a class Named Movie which have 3 fields – id, name and genre

Create a list of movies and convert with to map with name as key and genre as value.

Create a class Named ConvertListToMapMain

Output:

{Interstellar=SciFi, Matrix=SciFi, The Hangover=Comedy, Forest gump=Comedy, 3 idiots=Comedy}

moviesMap contains name as key and genre as value.
We can also use method references instead of lamda expressions.

What happens in case of a duplicate key?

In case, duplicate keys are present, then it will throw java.lang.IllegalStateException exception.

Let’s say we have two movies with name Matrix

When you run ConvertListToMapMain again, you will get below output:
Output:

Exception in thread “main” java.lang.IllegalStateException: Duplicate key Sci Fi
at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
at java.util.HashMap.merge(HashMap.java:1254)
at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:566)
at org.arpit.java2blog.ConvertListToMapMain.main(ConvertListToMapMain.java:14)

To resolve this issue, we need to pass merge BinaryOperator function to Collectors.toMap().

When you run ConvertListToMapMain again, you will get below output:
Output:

{Matrix=Comedy, Interstellar=SciFi, Forest gump=Comedy, 3 idiots=Comedy}

What if you want specific Map such as TreeMap?

You can pass constructor method reference to Collectors.toMap() to get specific map.

When you run ConvertListToMapMain again, you will get below output:
Output:

{3 idiots=Comedy, Forest gump=Comedy, Interstellar=SciFi, Matrix=Comedy}

As you can see, we have TreeMap which is sorted by name.

Get multiMap with Collectors.groupingBy()

In case, you want movie grouped by genre as key and name as value, then you can use Collectors.groupingBy() and Collectors.mapping as below:

Output:

{Comedy=[3 idiots, Forest gump, The Hangover], SciFi=[Interstellar, Matrix]}

As you can see, moviesGenMap has genre as key and list of movies name as value.

Excercise

Given a list of Employee objects, you need to convert list to Map with name as key and age as value. In case, there are duplicate keys, then you need to preserve old value.
Here is the definition of Employee class.

That’s all about Java stream List to Map


import_contacts

You may also like:

Related Posts

  • 09 January

    Convert set to String in Python

    Table of ContentsWays to convert set to string in PythonUsing the str() functionUsing the repr() functionUsing the join() functionUsing the map() functionConclusion Sets are an unordered collection of elements in Python. It does not contain duplicate elements and can be defined using the set() function in Python. Ways to convert set to string in Python […]

  • Convert String to Array in java
    11 December

    Convert String to Array in Java

    Table of ContentsHow to convert String to Array in JavaUsing toArray() method of SetUsing the split() method of String classUsing StringTokenizor classUsing the split() method of StringUtils classUsing split() method of Pattern classConclusion When developing applications in Java there are many cases where we will find ourselves converting data from one type to the other. […]

  • Convert float to int in Python
    19 June

    Convert float to int in Python

    Table of ContentsUsing the int() function to convert float to int in PythonUsing the math module functions to convert float to int in PythonUsing ceil()Using trunc()Using floor Python provides several in-built functions and modules for datatype conversions. Floating-point numbers can be easily converted to integers using some of these in-built functions. This tutorial will discuss […]

  • Java BigDecimal to Double
    17 May

    Java BigDecimal to Double

    Learn about how to convert BigDecimal to Double in java

  • Java Set to Array
    12 May

    Java Set to Array

    Table of Contents1. Using Java 8’s Stream2. Using toArray()3. Using toArray(IntFunction) [Java 11]4. Using System.arraycopy()5. Using Arrays.copyOf6. Using simple iteration7. Using Guava library7.1 Using FluentIterable7.2 Using Iterables In this post, we will learn java set to array conversion. There are many ways to convert set to an array. 1. Using Java 8’s Stream If you […]

  • Convert Date to LocalDate in java
    12 January

    Java Date to LocalDate

    Table of ContentsUsing toInstant() method of Date classUsing toInstant() method of Date classUsing java.sql.Date In this post, we will see how to convert Date to LocalDate in java. Sometimes, we may need to convert Date to new Java 8 APIs and vice versa. There are multiple ways to convert Date to LocalDate in java. Read […]

Comments

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.