Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a static Map of String -> Array

Tags:

java

static

map

I need to create a static Map which maps a given String to an array of int's.

In other words, I'd like to define something like:

"fred" -> {1,2,5,8}
"dave" -> {5,6,8,10,11}
"bart" -> {7,22,10010}
... etc

Is there an easy way to do this in Java?

And if possible, I'd like to use static constants for both the String and the int values.

EDIT: To clarify what I meant by static constants for the values, and to give what I see to be the correct code, here is my first stab at the solution:

public final static String FRED_TEXT = "fred";
public final static String DAVE_TEXT = "dave";

public final static int ONE = 1;
public final static int TWO = 2;
public final static int THREE = 3;
public final static int FOUR = 4;

public final static HashMap<String, int[]> myMap = new HashMap<String, int[]>();
static {
    myMap.put(FRED_TEXT, new int[] {ONE, TWO, FOUR});
    myMap.put(DAVE_TEXT, new int[] {TWO, THREE});
}

Note, these names are not what I'd actually be using. This is just a contrived example.

like image 303
DuncanKinnear Avatar asked Nov 18 '12 23:11

DuncanKinnear


People also ask

How do I create a static map in Java 8?

We can use Java 8 Stream to construct static maps by obtaining stream from static factory methods like Stream. of() or Arrays. stream() and accumulating the input elements into a new map using collectors.

How do I create a static map in TypeScript?

Use the Map() constructor to initialize a Map in TypeScript, e.g. const map1: Map<string, string> = new Map([['name', 'Tom']]) . The constructor takes an array containing nested arrays of key-value pairs, where the first element is the key and the second - the value. Copied!

What is map of () in Java?

Java 9 feature – Map.of() method In Java 9, Map. of() was introduced which is a convenient way to create instances of Map interface. It can hold up to 10 key-value pairs.


1 Answers

You need to declare and initialize your static map separately.

Here is the declaration piece:

private static final Map<String,int[]> MyMap;

Here is the initialization piece:

static {
    Map<String,int[]> tmpMap = new HashMap<String,int[]>();
    tmpMap.put("fred", new int[] {1,2,5,8});
    tmpMap.put("dave", new int[] {5,6,8,10,11});
    tmpMap.put("bart", new int[] {7,22,10010});
    MyMap = Collections.unmodifiableMap(tmpMap);
}

Unfortunately, arrays are always writable in Java. You wouldn't be able to assign MyMap, but you would be able to add or remove values from other parts of your program that accesses the map.

like image 87
Sergey Kalinichenko Avatar answered Sep 20 '22 08:09

Sergey Kalinichenko