How to initialize HashMap amongst values inward Java? One liner

There is oft a province of affairs where you lot would similar to do a HashMap amongst unopen to pre-defined mapping, but unfortunately, Java doesn't render map literals similar Groovy or Scala to do the map amongst values inward the same line. If you lot remember, nosotros accept faced the same outcome amongst other Collection classes every bit good e.g. ArrayList, Vector or LinkedList. But ArrayList is lucky because you lot tin even thus utilization the Arrays.asList() method to do too initialize the ArrayList inward simply ane business every bit shown here. But, how do you lot initialize the HashMap amongst values inward Java? There is no such method similar Arrays.asMap() or Collections.asMap(), too this is non simply the inquiry well-nigh HashMap but likewise well-nigh Hashtable, LinkedHashMap too ConcurrentHashMap. Well, at that spot is an idiom called double pair initialization, which you lot tin utilization to initialize the HashMap at the fourth dimension of declaration. I'll demonstrate you lot how to utilization that double pair initialization to do HashMap amongst values inward this article amongst a uncomplicated example.



How to do HashMap amongst values inward Java

As I told you lot tin utilization the Double pair initialization to do HashMap amongst values. Btw, this is non a rattling practiced pattern, inward fact, it is considered every bit an anti-pattern inward Java, but if you lot are doing this simply for utility or testing utilization than it's ok. This idiom internally uses the event initializer of Anonymous inner class too damage an extra course of teaching every fourth dimension you lot utilization it, but you lot tin utilization it to initialize both static too non-static HashMap every bit shown inward 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 inward Java application.

 There is oft a province of affairs where you lot would similar to do a HashMap amongst unopen to pre How to initialize HashMap amongst values inward Java? One liner


The practiced affair well-nigh this idiom is that It requires less code i.e. you lot don't necessitate to do HashMap without values too and thus afterwards telephone squall upwardly the put() method, but you lot tin both do too initialize the Map inward the same line. You tin likewise utilization double pair initialization amongst LinkedHashMap, TreeMap, ConcurrentHashMap, too Hashtable, inward fact, amongst whatever Map implementation e.g. EnumMap too WeakHashMAp.




Java Program to do HashMap amongst values

Here is our sample Java plan to do too initialize the HashMap inward the same line.  In this example, nosotros accept used the double pair initialization idiom to initialize both static too non-static HashMap. If you lot await our program, you lot volition abide by that nosotros accept a map called squares which are supposed to incorporate the break too it's square. This HashMap is initialized inward the static initializer block.  Then, nosotros accept unopen to other Integer to String Map called IdToName, this is likewise created too initialized at the same line.

import java.util.HashMap; import java.util.Map;  /**  * Java Program to demonstrate you lot tin initialize a HashMap wit values inward ane line.  * You tin utilization this technique to initialize static Maps inward 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 too Cons

Though this technique, double pair initialization looks bang-up when you lot commencement larn well-nigh it, it has its shares of problems every bit discussed inward the minute paragraph. Let's encounter the advantages too disadvantage of double pair initialization pattern for quick reference:

Advantages:
1) less business of code
2) Instantiation too initialization inward the same expression.

Disadvantages:
1) Not rattling readable. This idiom internally uses the Anonymous inner class, which is non clear yesteryear simply looking at it.
2) It creates a novel course of teaching every fourth dimension you lot utilization this designing to initialize HashMap.
3) It holds a hidden reference of the enclosing instance, which may crusade the retentivity leak inward Java application.


That's all well-nigh how to initialize HashMap inward Java inward ane line. You tin utilization the double pair initialization designing to do HashMap amongst values but beware of all the disadvantages associated amongst this idiom. It's practiced for testing too demo utilization but I don't suggest you lot to utilization this technique inward production. Instead, charge information from database or config file.

Further Learning
Java Fundamentals: Collections
From Collections to Streams inward Java 8 Using Lambda Expressions
Grokking Algorithms yesteryear Aditya Bhargava
Java Programming Interview Exposed yesteryear Makham

Other Java collection tutorials you lot may like
The divergence betwixt HashMap too LinkedHashMap inward Java? (answer)
The best means to iterate over HashMap inward Java? (answer)
How to form the HashMap on keys too values inward Java? (solution)
iii ways to loop over a Map inward Java? (example)
The divergence betwixt HashMap too ConcurrentHashMap inward Java? (answer)
Java Generics too Collections - The Ultimate mass on Java Collections (see here)

Subscribe to receive free email updates:

0 Response to "How to initialize HashMap amongst values inward Java? One liner"

Posting Komentar