10 Examples Of Converting A Listing To Map Inwards Coffee 8
Saturday, December 15, 2018
Add Comment
Suppose you lot receive got a List of objects, List in addition to you lot desire to convert that to a Map, where a primal is obtained from the object in addition to value is the object itself, how create you lot create it past times using Java 8 current in addition to lambda expression? Prior to Java 8, you lot tin create this past times iterating through the List in addition to populating the map past times keys the in addition to values. Since it's iterative approach in addition to if you lot are looking for a functional solution in addition to then you lot require to usage the current in addition to lambda expression, along amongst just about 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 usage the Collectors.groupingBy() method to grouping elements inward Set in addition to In this article, nosotros volition usage Collectors.toMap() method to convert a List of an object into a Map inward Java.
Remember, the Map returned past times Collector is non necessarily HashMap or LinkedHashMap, if you lot desire to usage whatever particular Map type, you lot require to say the Collector most it every bit shown inward the minute example.
In the similar note, if you lot receive got just started learning Java 8 in addition to come upward hither to solve a occupation you lot are facing inward your twenty-four hours to twenty-four hours life spell converting a Java SE vi or seven code to Java 8, in addition to then I advise going through a mass similar Java SE 8 for Really Impatient. It's 1 of the improve books amongst amount of non-trivial illustration in addition to 1 time you lot went through that you lot won't require to await upward Google for your twenty-four hours to twenty-four hours chore inward Java 8.
Before Java 8
Here is how you lot tin convert a List to Map inward Java 5, vi or 7:
You tin meet nosotros receive got iterated through the List using enhanced for loop of Java 5 in addition to set the each chemical ingredient into a HashMap, where ISBN code is the primal in addition to mass object itself is the value. This is the best way to convert a List to Map inward pre-JDK 8 worlds. It's clear, concise in addition to self-explanatory, but iterative.
Java 8 using Lambdas
Now, let's meet how nosotros tin create the same inward Java 8 past times using lambda aspect in addition to Stream API, hither is my commencement attempt:
In to a higher house code example, the stream() method render a current of Book object from the List in addition to and then I receive got used collect() method of Stream course of didactics to collect all elements. All the magic of how to collect elements happening inward this method.
I receive got passed the method Collectors.toMap(), which agency elements volition move collected inward a Map, where the primal volition move ISBN code in addition to value volition move the object itself. We receive got used a lambda expression to simplify the code.
Using Java 8 method reference
You tin farther only the code inward Java 8 past times using method reference, every bit shown below:
Here nosotros receive got called the getISBN() method using method reference instead of using a lambda expression.
You tin farther take away the in conclusion remaining lambda aspect from this code, where nosotros are passing the object itself past times using Function.identify() method inward Java 8 when the value of the Map is the object itself, every bit shown below:
What does position component subdivision create here? It's just a substitute of b ->b in addition to you lot tin usage if you lot desire to overstep the object itself. See Java SE 8 for Really Impatient to larn to a greater extent than most Function.identity() method.
Well, the to a higher house method volition throw IllegalStateException every bit shown inward the next example:
Exception inward 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 ingredient of the List is a duplicate key. Now how create you lot solve this problem? Well, Java 8 has provided just about other overloaded version of Collectors.toMap() component subdivision which accepts a merge component subdivision to create upward one's heed what to create inward instance of the duplicate key. If you lot usage that version, instead of throwing an exception, Collector volition usage that merge component subdivision to resolve a conflict.
In the next example, I receive got used that version in addition to instructed to usage the commencement object inward instance of the duplicate key, the lambda aspect (e1, e2) -> e1 is suggesting that.
You tin create whatever you lot desire e.g. you lot tin combine the keys or direct whatever 1 of them.
You tin meet that List contains 4 elements but our Map contains solely iii mappings because 1 of the chemical ingredient "Visa" is duplicate. The Collector solely kept the commencement reference of "Visa" in addition to discarded the minute one. Alternatively, you lot tin besides take away duplicates from List earlier converting it to Map every bit shown here.
If you lot actually require elements inward Map inward the same guild they were inward the List, you lot tin usage just about other version of Collectors.toMap() method which accepts 4 parameters in addition to the in conclusion 1 of them is to enquire for a specific Map implementation e.g. HashMap or LinkedHaashMap.
Since LinkedHashMap maintains insertion guild of elements (see here), you lot tin collection elements inward the LinkedHashMap every bit shown inward the next example:
You tin meet that guild of elements inward both List in addition to Map are precisely same. So usage this version of Collectors.toMap() method if you lot desire to save ordering of elements inward the Map.
That's all most how to convert a List to Map inward Java 8 using lambda aspect in addition to Streams. You tin meet it's much easier in addition to concise using the lambda expression. Just retrieve 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 guild of elements if you lot desire to proceed the guild same every bit inward master copy listing in addition to then usage the LinkedHashMap every bit shown inward the in conclusion example.
Also, don't forget to furnish a merge component subdivision if you lot are non certain most whether your List volition comprise duplicates or not. It volition forbid the IllegalStateException you lot acquire when your List contains duplicates in addition to you lot desire to convert it to a Map, which doesn't allow duplicate keys.
Further Learning
The Complete Java MasterClass
tutorial)How to usage Stream course of didactics inward Java 8 (tutorial) How to usage filter() method inward Java 8 (tutorial) How to usage forEach() method inward Java 8 (example) How to bring together String inward Java 8 (example) How to convert List to Map inward Java 8 (solution) How to usage peek() method inward Java 8 (example) 5 Books to Learn Java 8 from Scratch (books) How to convert current to array inward Java 8 (tutorial) Java 8 Certification FAQ (guide) Java 8 Mock Exams in addition to Practice Test (test)
Thanks for reading this article thus far. If you lot similar this article in addition to then delight percentage amongst your friends in addition to colleagues. If you lot receive got whatever question, doubt, or feedback in addition to then delight drib a comment in addition to I'll seek to respond your question.
Sumber https://javarevisited.blogspot.com/
Remember, the Map returned past times Collector is non necessarily HashMap or LinkedHashMap, if you lot desire to usage whatever particular Map type, you lot require to say the Collector most it every bit shown inward the minute example.
In the similar note, if you lot receive got just started learning Java 8 in addition to come upward hither to solve a occupation you lot are facing inward your twenty-four hours to twenty-four hours life spell converting a Java SE vi or seven code to Java 8, in addition to then I advise going through a mass similar Java SE 8 for Really Impatient. It's 1 of the improve books amongst amount of non-trivial illustration in addition to 1 time you lot went through that you lot won't require to await upward Google for your twenty-four hours to twenty-four hours chore inward Java 8.
How to convert a List to Map inward Java
Now, let's meet dissimilar ways to solve this occupation inward the pre-JDK 8 globe in addition to inward Java 8. This comparative analysis volition assist you lot to larn the concept in addition to Java 8 API better.Before Java 8
Here is how you lot tin convert a List to Map inward Java 5, vi or 7:
private Map<String, Choice> toMap(List books) { final Map hashMap = new HashMap<>(); for (final Book mass : 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 in addition to set the each chemical ingredient into a HashMap, where ISBN code is the primal in addition to mass object itself is the value. This is the best way to convert a List to Map inward pre-JDK 8 worlds. It's clear, concise in addition to self-explanatory, but iterative.
Java 8 using Lambdas
Now, let's meet how nosotros tin create the same inward Java 8 past times using lambda aspect in addition to Stream API, hither is my commencement attempt:
Map<String, Book> trial = books.stream() .collect(Collectors.toMap(book -> book.getISBN, mass -> book));
In to a higher house code example, the stream() method render a current of Book object from the List in addition to and then I receive got used collect() method of Stream course of didactics to collect all elements. All the magic of how to collect elements happening inward this method.
I receive got passed the method Collectors.toMap(), which agency elements volition move collected inward a Map, where the primal volition move ISBN code in addition to value volition move the object itself. We receive got used a lambda expression to simplify the code.
Using Java 8 method reference
You tin farther only the code inward Java 8 past times using method reference, every bit shown below:
Map<String, Book> trial = 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 away the in conclusion remaining lambda aspect from this code, where nosotros are passing the object itself past times using Function.identify() method inward Java 8 when the value of the Map is the object itself, every bit shown below:
Map<String, Book> trial = choices.stream() .collect(Collectors.toMap(Book::getISBN, Function.identity()))
What does position component subdivision create here? It's just a substitute of b ->b in addition to you lot tin usage if you lot desire to overstep the object itself. See Java SE 8 for Really Impatient to larn to a greater extent than most Function.identity() method.
How to convert a List amongst Duplicates into Map inward 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 come about if you lot seek to convert a List amongst duplicate elements into a Map inward Java 8?Well, the to a higher house method volition throw IllegalStateException every bit shown inward the next example:
List cards = Arrays.asList("Visa", "MasterCard", "American Express", "Visa"); Map cards2Length = cards.stream() .collect(Collectors.toMap(Function.identity(), String::length));
Exception inward 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 ingredient of the List is a duplicate key. Now how create you lot solve this problem? Well, Java 8 has provided just about other overloaded version of Collectors.toMap() component subdivision which accepts a merge component subdivision to create upward one's heed what to create inward instance of the duplicate key. If you lot usage that version, instead of throwing an exception, Collector volition usage that merge component subdivision to resolve a conflict.
In the next example, I receive got used that version in addition to instructed to usage the commencement object inward instance of the duplicate key, the lambda aspect (e1, e2) -> e1 is suggesting that.
You tin create whatever you lot desire e.g. you lot tin combine the keys or direct whatever 1 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 solely iii mappings because 1 of the chemical ingredient "Visa" is duplicate. The Collector solely kept the commencement reference of "Visa" in addition to discarded the minute one. Alternatively, you lot tin besides take away 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 uncomplicated implementation of Map interface in addition to because Map doesn't guarantee the guild of mappings, you lot volition probable to lose the ordering of chemical ingredient provided past times the List interface.If you lot actually require elements inward Map inward the same guild they were inward the List, you lot tin usage just about other version of Collectors.toMap() method which accepts 4 parameters in addition to the in conclusion 1 of them is to enquire for a specific Map implementation e.g. HashMap or LinkedHaashMap.
Since LinkedHashMap maintains insertion guild of elements (see here), you lot tin collection elements inward the LinkedHashMap every bit shown inward 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 inward Java 8. * This illustration shows a push clitoris a fast 1 on to save guild of chemical ingredient * inward the listing spell 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 guild of elements inward both List in addition to Map are precisely same. So usage this version of Collectors.toMap() method if you lot desire to save ordering of elements inward the Map.
That's all most how to convert a List to Map inward Java 8 using lambda aspect in addition to Streams. You tin meet it's much easier in addition to concise using the lambda expression. Just retrieve 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 guild of elements if you lot desire to proceed the guild same every bit inward master copy listing in addition to then usage the LinkedHashMap every bit shown inward the in conclusion example.
Also, don't forget to furnish a merge component subdivision if you lot are non certain most whether your List volition comprise duplicates or not. It volition forbid the IllegalStateException you lot acquire when your List contains duplicates in addition to 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 in addition to then delight percentage amongst your friends in addition to colleagues. If you lot receive got whatever question, doubt, or feedback in addition to then delight drib a comment in addition to I'll seek to respond your question.
0 Response to "10 Examples Of Converting A Listing To Map Inwards Coffee 8"
Post a Comment