0

I want to store a small number (eg. 20) of key value pairs in Java. I know the values beforehand, and they won't change. I just need to be able to access them somehow to use in my calculations. In JavaScript, I would simply hard-code an object for this purpose. So my first idea was to use a map. However, from what I've seen, I can't explicitly initialise a map (map = { "key1": 1, "key2": 2, ...}) but would have to call map.put() twenty times. Is there another way? Or is there perhaps a different data structure better suited for this purpose? Or would the easiest way be to store the data in a file, and then read it at runtime, and if so, what filetype works best for this / with Java?

muell
  • 383
  • 1
  • 15

1 Answers1

0

Starting with Java 9, you can initialize a Map from given values by using Map.ofEntries(...) and the Map.entry(k,v) function:

private static final Map<String,Integer> m = Map.ofEntries(
        Map.entry("a", 1),
        Map.entry("b", 2)
);

The resulting Map is immutable. null is not allowed as a key, and duplicate keys aren't allowed either.

If you want the values to be stored outside of your code, then you can use any data format that preserves the types (e.g. JSON). You can store the data in a a properties file that gets embedded into to compiled artifact, then read back via ClassLoader.getResourceAsStream(name) and then convert the binary data to your data structure / Map.

jCoder
  • 2,289
  • 23
  • 22