10 Examples Of Converting A Listing To Map Inwards Coffee 8
Suppose you lot direct hold a List of objects, List as well as you lot desire to convert that to a Map, where a telephone commutation is obtained from the object as well as value is the object itself, how create you lot create it past times using Java 8 current as well as lambda expression? Prior to Java 8, you lot tin strength out create this past times iterating through the List as well as populating the map past times keys the as well as values. Since it's iterative approach as well as if you lot are looking for a functional solution thus you lot involve to occupation the current as well as lambda expression, along amongst about utility classes similar Collectors, which provides several useful methods to convert Stream to List, Set or Map. In the past, nosotros direct hold seen how to occupation the Collectors.groupingBy() method to grouping elements inwards Set as well as In this article, nosotros volition occupation Collectors.toMap() method to convert a List of an object into a Map inwards Java.
Remember, the Map returned past times Collector is non necessarily HashMap or LinkedHashMap, if you lot desire to occupation whatever exceptional Map type, you lot involve to say the Collector nearly it every bit shown inwards the 2d example.
In the similar note, if you lot direct hold just started learning Java 8 as well as come upwardly hither to solve a job you lot are facing inwards your twenty-four hr menses to twenty-four hr menses life acre converting a Java SE vi or vii code to Java 8, thus I propose going through a majority similar Java SE 8 for Really Impatient. It's i of the amend books amongst amount of non-trivial instance as well as in i lawsuit you lot went through that you lot won't involve to hold back upwardly Google for your twenty-four hr menses to twenty-four hr menses business inwards Java 8.
Before Java 8
Here is how you lot tin strength out convert a List to Map inwards Java 5, vi or 7:
You tin strength out run into nosotros direct hold iterated through the List using enhanced for loop of Java 5 as well as pose the each chemical constituent into a HashMap, where ISBN code is the telephone commutation 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 run into how nosotros tin strength out create the same inwards Java 8 past times using lambda seem as well as Stream API, hither is my outset attempt:
In to a higher house code example, the stream() method render a current of Book object from the List as well as thus I direct hold used collect() method of Stream flat to collect all elements. All the magic of how to collect elements happening inwards this method.
I direct hold passed the method Collectors.toMap(), which agency elements volition locomote collected inwards a Map, where the telephone commutation volition locomote ISBN code as well as value volition locomote the object itself. We direct hold used a lambda expression to simplify the code.
Using Java 8 method reference
You tin strength out farther only the code inwards Java 8 past times using method reference, every bit shown below:
Here nosotros direct hold called the getISBN() method using method reference instead of using a lambda expression.
You tin strength out farther take the in conclusion remaining lambda seem from this code, where nosotros are passing the object itself past times using Function.identify() method inwards Java 8 when the value of the Map is the object itself, every bit shown below:
What does position component create here? It's just a substitute of b ->b as well as you lot tin strength out occupation if you lot desire to transcend the object itself. See Java SE 8 for Really Impatient to acquire to a greater extent than nearly Function.identity() method.
Well, the to a higher house method volition throw IllegalStateException every bit shown inwards the next example:
Exception inwards thread "main" java.lang.IllegalStateException: Duplicate telephone commutation 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 create you lot solve this problem? Well, Java 8 has provided about other overloaded version of Collectors.toMap() component which accepts a merge component to create upwardly one's heed what to create inwards instance of the duplicate key. If you lot occupation that version, instead of throwing an exception, Collector volition occupation that merge component to resolve a conflict.
In the next example, I direct hold used that version as well as instructed to occupation the outset object inwards instance of the duplicate key, the lambda seem (e1, e2) -> e1 is suggesting that.
You tin strength out create whatever you lot desire e.g. you lot tin strength out combine the keys or direct whatever i of them.
You tin strength out run into that List contains 4 elements but our Map contains entirely iii mappings because i of the chemical constituent "Visa" is duplicate. The Collector entirely kept the outset reference of "Visa" as well as discarded the 2d one. Alternatively, you lot tin strength out too take duplicates from List earlier converting it to Map every bit shown here.
If you lot actually involve elements inwards Map inwards the same gild they were inwards the List, you lot tin strength out occupation about other version of Collectors.toMap() method which accepts 4 parameters as well as the in conclusion i of them is to enquire for a specific Map implementation e.g. HashMap or LinkedHaashMap.
Since LinkedHashMap maintains insertion gild of elements (see here), you lot tin strength out collection elements inwards the LinkedHashMap every bit shown inwards the next example:
You tin strength out run into that gild of elements inwards both List as well as Map are just same. So occupation this version of Collectors.toMap() method if you lot 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 strength out run into it's much easier as well as concise using the lambda expression. Just think that the Map returned past times 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 you lot desire to drib dead on the gild same every bit inwards master listing thus occupation the LinkedHashMap every bit shown inwards the in conclusion example.
Also, don't forget to render a merge component if you lot are non certain nearly whether your List volition comprise duplicates or not. It volition forbid the IllegalStateException you lot acquire when your List contains duplicates as well as you lot desire to convert it to a Map, which doesn't allow duplicate keys.
Further Learning
The Complete Java MasterClass
tutorial)How to occupation Stream flat inwards Java 8 (tutorial) How to occupation filter() method inwards Java 8 (tutorial) How to occupation 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 occupation 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 you lot similar this article thus delight portion amongst your friends as well as colleagues. If you lot direct hold whatever question, doubt, or feedback thus delight drib a comment as well as I'll assay to response your question.
Remember, the Map returned past times Collector is non necessarily HashMap or LinkedHashMap, if you lot desire to occupation whatever exceptional Map type, you lot involve to say the Collector nearly it every bit shown inwards the 2d example.
In the similar note, if you lot direct hold just started learning Java 8 as well as come upwardly hither to solve a job you lot are facing inwards your twenty-four hr menses to twenty-four hr menses life acre converting a Java SE vi or vii code to Java 8, thus I propose going through a majority similar Java SE 8 for Really Impatient. It's i of the amend books amongst amount of non-trivial instance as well as in i lawsuit you lot went through that you lot won't involve to hold back upwardly Google for your twenty-four hr menses to twenty-four hr menses business inwards Java 8.
How to convert a List to Map inwards Java
Now, let's run into dissimilar ways to solve this job inwards the pre-JDK 8 basis as well as inwards Java 8. This comparative analysis volition assist you lot to acquire the concept as well as Java 8 API better.Before Java 8
Here is how you lot tin strength out 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 strength out run into nosotros direct hold iterated through the List using enhanced for loop of Java 5 as well as pose the each chemical constituent into a HashMap, where ISBN code is the telephone commutation 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 run into how nosotros tin strength out create the same inwards Java 8 past times using lambda seem as well as Stream API, hither is my outset attempt:
Map<String, Book> resultant = books.stream() .collect(Collectors.toMap(book -> book.getISBN, majority -> book));
In to a higher house code example, the stream() method render a current of Book object from the List as well as thus I direct hold used collect() method of Stream flat to collect all elements. All the magic of how to collect elements happening inwards this method.
I direct hold passed the method Collectors.toMap(), which agency elements volition locomote collected inwards a Map, where the telephone commutation volition locomote ISBN code as well as value volition locomote the object itself. We direct hold used a lambda expression to simplify the code.
Using Java 8 method reference
You tin strength out farther only the code inwards Java 8 past times using method reference, every bit shown below:
Map<String, Book> resultant = books.stream() .collect(Collectors.toMap(Book::getISBN, b -> b));
Here nosotros direct hold called the getISBN() method using method reference instead of using a lambda expression.
You tin strength out farther take the in conclusion remaining lambda seem from this code, where nosotros are passing the object itself past times using Function.identify() method inwards Java 8 when the value of the Map is the object itself, every bit shown below:
Map<String, Book> resultant = choices.stream() .collect(Collectors.toMap(Book::getISBN, Function.identity()))
What does position component create here? It's just a substitute of b ->b as well as you lot tin strength out occupation if you lot desire to transcend the object itself. See Java SE 8 for Really Impatient to acquire to a greater extent than nearly Function.identity() method.
How to convert a List amongst Duplicates into Map inwards JDK 8
What if List has duplicates? When you lot are converting List to Map, you lot must pay attending to a dissimilar feature of these ii collection classes, a List allows duplicate elements, but Map doesn't allow duplicate keys. What volition locomote on if you lot assay to convert a List amongst duplicate elements into a Map inwards Java 8?Well, the to a higher house method volition throw IllegalStateException every bit 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 telephone commutation 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 create you lot solve this problem? Well, Java 8 has provided about other overloaded version of Collectors.toMap() component which accepts a merge component to create upwardly one's heed what to create inwards instance of the duplicate key. If you lot occupation that version, instead of throwing an exception, Collector volition occupation that merge component to resolve a conflict.
In the next example, I direct hold used that version as well as instructed to occupation the outset object inwards instance of the duplicate key, the lambda seem (e1, e2) -> e1 is suggesting that.
You tin strength out create whatever you lot desire e.g. you lot tin strength out 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 strength out run into that List contains 4 elements but our Map contains entirely iii mappings because i of the chemical constituent "Visa" is duplicate. The Collector entirely kept the outset reference of "Visa" as well as discarded the 2d one. Alternatively, you lot tin strength out too take duplicates from List earlier converting it to Map every bit shown here.
How to Preserve Order of Elements when converting a List to Map
Remember I said that Map returned past times the Collectors.toMap() is a just a unproblematic implementation of Map interface as well as because Map doesn't guarantee the gild of mappings, you lot volition probable to lose the ordering of chemical constituent provided past times the List interface.If you lot actually involve elements inwards Map inwards the same gild they were inwards the List, you lot tin strength out occupation about other version of Collectors.toMap() method which accepts 4 parameters as well as the in conclusion i of them is to enquire for a specific Map implementation e.g. HashMap or LinkedHaashMap.
Since LinkedHashMap maintains insertion gild of elements (see here), you lot tin strength out collection elements inwards the LinkedHashMap every bit 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 instance shows a play a trick on 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 strength out run into that gild of elements inwards both List as well as Map are just same. So occupation this version of Collectors.toMap() method if you lot 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 strength out run into it's much easier as well as concise using the lambda expression. Just think that the Map returned past times 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 you lot desire to drib dead on the gild same every bit inwards master listing thus occupation the LinkedHashMap every bit shown inwards the in conclusion example.
Also, don't forget to render a merge component if you lot are non certain nearly whether your List volition comprise duplicates or not. It volition forbid the IllegalStateException you lot acquire when your List contains duplicates as well as you lot desire to convert it to a Map, which doesn't allow duplicate keys.
Further Learning
The Complete Java MasterClass
tutorial)
Thanks for reading this article thus far. If you lot similar this article thus delight portion amongst your friends as well as colleagues. If you lot direct hold whatever question, doubt, or feedback thus delight drib a comment as well as I'll assay to response your question.
0 Response to "10 Examples Of Converting A Listing To Map Inwards Coffee 8"
Post a Comment