0

How would you initialise a static Map in Java?

Method one: Create a Class extend from Hashmap as below

Here is an example illustrating the way i did using a CustomMap:

Ramkumar Pillai
  • 154
  • 2
  • 8
  • Is this what you are looking for? http://stackoverflow.com/questions/6802483/how-to-directly-initialize-a-hashmap-in-a-literal-way – Vishal May 01 '16 at 13:18
  • @Vishal :- FYI- found solution and it is there below as answer – Ramkumar Pillai May 14 '16 at 03:58
  • 2
    Possible duplicate of [How can I Initialize a static Map?](http://stackoverflow.com/questions/507602/how-can-i-initialize-a-static-map) – Didier L Jun 29 '16 at 16:15

1 Answers1

0
public class CustomMap < K, V > extends java.util.HashMap < K, V > {

  public CustomMap(Object[]...objs) {
    super();
    this.of(objs);
  }

  public java.util.Map < K, V > of(Object[]...objs) {
    for (Object[] o: objs) {
      this.of((K) o[0], (V) o[1]);
    }
    return this;
  }

  public java.util.Map < K, V > of(K k, V v) {
    this.put(k, v);
    return this;
  }

  public static Object[] tuple(Object k, Object v) {
    return new Object[] {
      k, v
    };
  }

  //USAGE
  public static void main(String...args) {
    //import static CustomMap.tuple;
    java.util.Map < String, String > cmap = new CustomMap < > (CustomMap.tuple("One", "Two"));
  }
}
Ramkumar Pillai
  • 154
  • 2
  • 8