10 Examples Of Converting A Listing To Map Inward Coffee 8

Suppose y'all receive got a List of objects, List as well as y'all desire to convert that to a Map, where a primal is obtained from the object as well as value is the object itself, how produce y'all produce it yesteryear using Java 8 current as well as lambda expression? Prior to Java 8, y'all tin produce this yesteryear iterating through the List as well as populating the map yesteryear keys the as well as values. Since it's iterative approach as well as if y'all are looking for a functional solution as well as thus y'all require to utilization the current as well as lambda expression, along alongside closed to utility classes similar Collectors, which provides several useful methods to convert Stream to List, Set or Map. In the past, nosotros receive got seen how to utilization the Collectors.groupingBy() method to grouping elements inwards Set as well as In this article, nosotros volition utilization Collectors.toMap() method to convert a List of an object into a Map inwards Java.

Remember, the Map returned yesteryear Collector is non necessarily HashMap or LinkedHashMap, if y'all desire to utilization whatever particular Map type, y'all require to say the Collector nearly it equally shown inwards the minute example.

In the similar note, if y'all receive got just started learning Java 8 as well as come upward hither to solve a work y'all are facing inwards your twenty-four hr menstruum to twenty-four hr menstruum life acre converting a Java SE vi or seven code to Java 8, as well as thus I advise going through a majority similar Java SE 8 for Really Impatient. It's i of the improve books alongside sum of non-trivial illustration as well as in i lawsuit y'all went through that y'all won't require to hold back upward Google for your twenty-four hr menstruum to twenty-four hr menstruum draw inwards Java 8.

 where a primal is obtained from the object as well as value is the object itself 10 Examples of Converting a List to Map inwards Java 8




How to convert a List to Map inwards Java

Now, let's meet unlike ways to solve this work inwards the pre-JDK 8 basis as well as inwards Java 8. This comparative analysis volition assist y'all to larn the concept as well as Java 8 API better.


Before Java 8
Here is how y'all tin convert a List to Map inwards Java 5, vi or 7:

private Map<String, Choice> toMap(List books) {         final Map hashMap = new HashMap<>();         for (final Book majority : books) {             hashMap.put(book.getISBN(), book);         }         return hashMap;     }

You tin meet nosotros receive got iterated through the List using enhanced for loop of Java 5 as well as lay the each chemical constituent into a HashMap, where ISBN code is the primal as well as majority object itself is the value. This is the best way to convert a List to Map inwards pre-JDK 8 worlds. It's clear, concise as well as self-explanatory, but iterative.


Java 8 using Lambdas
Now, let's meet how nosotros tin produce the same inwards Java 8 yesteryear using lambda seem as well as Stream API, hither is my get-go attempt:

Map<String, Book> effect  = books.stream()             .collect(Collectors.toMap(book -> book.getISBN, majority -> book));

In inwards a higher house code example, the stream() method render a current of Book object from the List as well as and thus I receive got used collect() method of Stream cast to collect all elements. All the magic of how to collect elements happening inwards this method.

I receive got passed the method Collectors.toMap(), which way elements volition live collected inwards a Map, where the primal volition live ISBN code as well as value volition live the object itself. We receive got used a lambda expression to simplify the code.




Using Java 8 method reference
You tin farther just the code inwards Java 8 yesteryear using method reference, equally shown below:

Map<String, Book> effect =  books.stream()         .collect(Collectors.toMap(Book::getISBN, b -> b));

Here nosotros receive got called the getISBN() method using method reference instead of using a lambda expression.


You tin farther take the lastly remaining lambda seem from this code, where nosotros are passing the object itself yesteryear using Function.identify() method inwards Java 8 when the value of the Map is the object itself, equally shown below:

Map<String, Book> effect = choices.stream()         .collect(Collectors.toMap(Book::getISBN, Function.identity()))

What does position business office produce here? It's just a substitute of b ->b as well as y'all tin utilization if y'all desire to overstep the object itself. See Java SE 8 for Really Impatient to larn to a greater extent than nearly Function.identity() method.

 where a primal is obtained from the object as well as value is the object itself 10 Examples of Converting a List to Map inwards Java 8


How to convert a List alongside Duplicates into Map inwards JDK 8

What if List has duplicates? When y'all are converting List to Map, y'all must pay attending to a unlike feature of these 2 collection classes, a List allows duplicate elements, but Map doesn't allow duplicate keys. What volition hap if y'all assay to convert a List alongside duplicate elements into a Map inwards Java 8?

Well, the inwards a higher house method volition throw IllegalStateException equally shown inwards the next example:

List cards = Arrays.asList("Visa", "MasterCard", "American Express", "Visa"); Map cards2Length = cards.stream()                 .collect(Collectors.toMap(Function.identity(), String::length));

Exception inwards thread "main" java.lang.IllegalStateException: Duplicate primal 4
at java.util.stream.Collectors.lambda$throwingMerger$90(Collectors.java:133)
at java.util.stream.Collectors$$Lambda$3/1555009629.apply(Unknown Source)
at java.util.HashMap.merge(HashMap.java:1245)
at java.util.stream.Collectors.lambda$toMap$148(Collectors.java:1320)
at java.util.stream.Collectors$$Lambda$5/258952499.accept(Unknown Source)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
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:499)
at Java8Demo.main(Java8Demo.java:20)

This exception is suggesting that 4th chemical constituent of the List is a duplicate key. Now how produce y'all solve this problem? Well, Java 8 has provided closed to other overloaded version of Collectors.toMap() business office which accepts a merge business office to create upward one's hear what to produce inwards instance of the duplicate key. If y'all utilization that version, instead of throwing an exception, Collector volition utilization that merge business office to resolve a conflict.

In the next example, I receive got used that version as well as instructed to utilization the get-go object inwards instance of the duplicate key, the lambda seem (e1, e2) -> e1 is suggesting that.

You tin produce whatever y'all desire e.g. y'all tin combine the keys or direct whatever i of them.

List cards = Arrays.asList("Visa", "MasterCard", "American Express", "Visa"); System.out.println("list: " + cards);          Map cards2Length = cards.stream()                 .collect(Collectors.toMap(Function.identity(), String::length, (e1, e2) -> e1)); System.out.println("map: " + cards2Length);  Output: list: [Visa, MasterCard, American Express, Visa
 map: {American Express=16, Visa=4, MasterCard=10}

You tin meet that List contains 4 elements but our Map contains exclusively 3 mappings because i of the chemical constituent "Visa" is duplicate. The Collector exclusively kept the get-go reference  of "Visa" as well as discarded the minute one. Alternatively, y'all tin too take duplicates from List earlier converting it to Map equally shown here.

 where a primal is obtained from the object as well as value is the object itself 10 Examples of Converting a List to Map inwards Java 8


How to Preserve Order of Elements when converting a List to Map

Remember I said that Map returned yesteryear the Collectors.toMap() is a just a unproblematic implementation of Map interface as well as because Map doesn't guarantee the gild of mappings, y'all volition probable to lose the ordering of chemical constituent provided yesteryear the List interface.

If y'all actually require elements inwards Map inwards the same gild they were inwards the List, y'all tin utilization closed to other version of Collectors.toMap() method which accepts 4 parameters as well as the lastly i of them is to inquire for a specific Map implementation e.g. HashMap or LinkedHaashMap.

Since LinkedHashMap maintains insertion gild of elements (see here), y'all tin collection elements inwards the LinkedHashMap equally shown inwards the next example:

import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors;  /*  * Java Program to convert a List to map inwards Java 8.  * This illustration shows a fob to save gild of chemical constituent  * inwards the listing acre converting to Map using LinkedHashMap.   */ public class Java8Demo {      public static void main(String args[]) {          List<String> hostingProviders = Arrays.asList("Bluehost", "GoDaddy", "Amazon AWS", "LiquidWeb", "FatCow");         System.out.println("list: " + hostingProviders);          Map<String, Integer> cards2Length = hostingProviders.stream()                 .collect(Collectors.toMap(Function.identity(),                                 String::length,                                 (e1, e2) -> e1,                                 LinkedHashMap::new));         System.out.println("map: " + cards2Length);      }  }  Output: list: [Bluehost, GoDaddy, Amazon AWS, LiquidWeb, FatCow] map: {Bluehost=8, GoDaddy=7, Amazon AWS=10, LiquidWeb=9, FatCow=6}

You tin meet that gild of elements inwards both List as well as Map are precisely same. So utilization this version of Collectors.toMap() method if y'all desire to save ordering of elements inwards the Map.



That's all nearly how to convert a List to Map inwards Java 8 using lambda seem as well as Streams. You tin meet it's much easier as well as concise using the lambda expression. Just retrieve that the Map returned yesteryear the Collectors.toMap() is non your regular HashMap, it just a  class which implements Map interface. It volition non save the gild of elements if y'all desire to continue the gild same equally inwards master copy listing as well as thus utilization the LinkedHashMap equally shown inwards the lastly example.

Also, don't forget to render a merge business office if y'all are non certain nearly whether your List volition comprise duplicates or not. It volition preclude the IllegalStateException y'all acquire when your List contains duplicates as well as y'all desire to convert it to a Map, which doesn't allow duplicate keys.

Further Learning
The Complete Java MasterClass
tutorial)
  • How to utilization Stream cast inwards Java 8 (tutorial)
  • How to utilization filter() method inwards Java 8 (tutorial)
  • How to utilization forEach() method inwards Java 8 (example)
  • How to bring together String inwards Java 8 (example)
  • How to convert List to Map inwards Java 8 (solution)
  • How to utilization peek() method inwards Java 8 (example)
  • 5 Books to Learn Java 8 from Scratch (books)
  • How to convert current to array inwards Java 8 (tutorial)
  • Java 8 Certification FAQ (guide)
  • Java 8 Mock Exams as well as Practice Test (test)

  • Thanks for reading this article thus far. If y'all similar this article as well as thus delight part alongside your friends as well as colleagues. If y'all receive got whatever question, doubt, or feedback as well as thus delight drib a comment as well as I'll assay to response your question.

    Komentar

    Postingan populer dari blog ini

    Difference Betwixt Struts Validatorform Vs Validatoractionform - Interview Question

    How To Convert Inputstream To Byte Array Inwards Coffee - Two Examples

    Difference Betwixt Fileinputstream Together With Filereader Inwards Coffee | Inputstream Vs Reader