Sunday, November 24, 2019

How To Initialize Hashmap Amongst Values Inwards Java? I Liner

There is oftentimes a province of affairs where y'all would similar to practise a HashMap alongside around pre-defined mapping, but unfortunately, Java doesn't furnish map literals similar Groovy or Scala to practise the map alongside values inwards the same line. If y'all remember, nosotros accept faced the same outcome alongside other Collection classes every bit good e.g. ArrayList, Vector or LinkedList. But ArrayList is lucky because y'all tin withal job the Arrays.asList() method to practise together with initialize the ArrayList inwards only i line of piece of work every bit shown here. But, how practise y'all initialize the HashMap alongside values inwards Java? There is no such method similar Arrays.asMap() or Collections.asMap(), together with this is non only the interrogation virtually HashMap but too virtually Hashtable, LinkedHashMap together with ConcurrentHashMap. Well, at that topographic point is an idiom called double yoke initialization, which y'all tin job to initialize the HashMap at the fourth dimension of declaration. I'll exhibit y'all how to job that double yoke initialization to practise HashMap alongside values inwards this article alongside a unproblematic example.



How to practise HashMap alongside values inwards Java

As I told y'all tin job the Double yoke initialization to practise HashMap alongside values. Btw, this is non a really proficient pattern, inwards fact, it is considered every bit an anti-pattern inwards Java, but if y'all are doing this only for utility or testing role than it's ok. This idiom internally uses the event initializer of Anonymous inner class together with toll an extra course of teaching every fourth dimension y'all job it, but y'all tin job it to initialize both static together with non-static HashMap every bit shown inwards our example. Another drawback of this idiom is that it holds  a hidden reference of enclosing course of teaching which may crusade the memory leak inwards Java application.

LinkedHashMap, TreeMap, ConcurrentHashMap, together with Hashtable, inwards fact, alongside whatever Map implementation e.g. EnumMap together with WeakHashMAp.




Java Program to practise HashMap alongside values

Here is our sample Java programme to practise together with initialize the HashMap inwards the same line.  In this example, nosotros accept used the double yoke initialization idiom to initialize both static together with non-static HashMap. If y'all await our program, y'all volition detect that nosotros accept a map called squares which are supposed to incorporate the disclose together with it's square. This HashMap is initialized inwards the static initializer block.  Then, nosotros accept around other Integer to String Map called IdToName, this is too created together with initialized at the same line.

import java.util.HashMap; import java.util.Map;  /**  * Java Program to exhibit y'all tin initialize a HashMap wit values inwards i line.  * You tin job this technique to initialize static Maps inwards Java.  *  * @author WINDOWS 8  */ public class HashMapWithValues {      private static final Map<Integer, Integer> squares;          static{       squares =   new HashMap<Integer, Integer>() {{             put(2, 4);             put(3, 9);             put(4, 16);         }};     }          public static void main(String args[]) {          Map<Integer, String> idToName = new HashMap<Integer, String>() {{             put(101, "John");             put(102, "John");             put(103, "John");         }};               System.out.println(idToName);         System.out.println(squares);     }  }  Output : {101=John, 102=John, 103=John} {2=4, 3=9, 4=16}


Pros together with Cons

Though this technique, double yoke initialization looks slap-up when y'all kickoff acquire virtually it, it has its shares of problems every bit discussed inwards the bit paragraph. Let's meet the advantages together with disadvantage of double yoke initialization pattern for quick reference:

Advantages:
1) less line of piece of work of code
2) Instantiation together with initialization inwards the same expression.

Disadvantages:
1) Not really readable. This idiom internally uses the Anonymous inner class, which is non clear past times only looking at it.
2) It creates a novel course of teaching every fourth dimension y'all job this blueprint to initialize HashMap.
3) It holds a hidden reference of the enclosing instance, which may crusade the retentivity leak inwards Java application.


That's all virtually how to initialize HashMap inwards Java inwards i line. You tin job the double yoke initialization blueprint to practise HashMap alongside values but beware of all the disadvantages associated alongside this idiom. It's proficient for testing together with demo role but I don't suggest y'all to job this technique inwards production. Instead, charge information from database or config file.

Further Learning
Java In-Depth: Become a Complete Java Engineer
answer)
The best means to iterate over HashMap inwards Java? (answer)
How to kind the HashMap on keys together with values inwards Java? (solution)
three ways to loop over a Map inwards Java? (example)
The divergence betwixt HashMap together with ConcurrentHashMap inwards Java? (answer)
Java Generics together with Collections - The Ultimate majority on Java Collections (see here)

No comments:

Post a Comment