-1

How do I write this in Java?

//js

const hello = {
  foo: "bar", 
  test: "world", 
  name: "david"
}

I want have a very long object, then refer it back like hello[test] or hello[foo]

I've heard of hashmaps, but you can only create an empty one and then add elements into it.

I've got a really long list like that in js. How can I copy those into Java? Doing .put() one by one would take forever, and I don't think that's efficient.

And even if someone wrote a script to turn uwu: "owo" into hello.put("uwu", "owo");, it'd be ugly in the code with a big block of hello.put()s.

I also don't want to create a new file for that (it only has around 34 lines) and want to keep it in the code. Also, because I have three more like these with 20-40 keys and values in each of them, I don't want to create three extra files with just 30 lines in them. I also don't want to go into complexity of reading them.

Oh and also, I won't be changing the hashmap btw, just reading data like a constant.

In summary, can I do something like this in Java for long lists without doing .put()?

public HashMap<String, String> hello = new HashMap<String, String>(
  "foo": "bar", 
  "test": "world", 
  "name": "david", 
  "uwu": "owo"
);

And refer to them like hello["name"]? I also don't want this thing.

public HashMap<String, String> hello = new HashMap<String, String>();
hello.put("foo", "bar");
hello.put("test", "world");
hello.put("name", "david");
hello.put("uwu", "owo");
//for 25 more lines

public HashMap<String, String> hello2 = new HashMap<String, String>();
hello2.put("stuff", "thing");
//... for around 20 more lines

//repeat for 3 more hashmaps
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
DavidNyan10
  • 163
  • 13
  • What Java version are you using? A lot of methods were added to the [Map](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Map.html) interface in Java 9. – Abra Mar 05 '22 at 07:08
  • Does this answer your question? [JavaScript-like Object data type in Java?](https://stackoverflow.com/questions/26785759/javascript-like-object-data-type-in-java) – Joe Mar 05 '22 at 07:59
  • @Abra The latest version, `java 17 2021-09-14 LTS` – DavidNyan10 Mar 06 '22 at 02:12
  • @Joe The answer uses what I don't want (a bunch of long `.put`s) – DavidNyan10 Mar 06 '22 at 02:15

3 Answers3

0

In modern Java (14 and later) you can use a record:

    record Hello(String foo, String test, String world) { }

and create an instance like this:

    final Hello hello = new Hello("bar", "world", "david");

You access the values like:

System.out.print(hello.foo());

Using a record has the advantage that your data is statically typed -- you can't mistype a key, or forget to remove usages of a key you've removed from the record.

tgdavies
  • 10,307
  • 4
  • 35
  • 40
0

IN Java 14 and beyond, I would recommand using a record, as explained in the other answer. It's the safest and also probably the most efficient way.

For Java 9 to 14, you may use Map.of("hello", "world", "foo", "bar");. But you may not be able to go beyond a certain number of key/value pairs.

For java 8 and below, or if you exceed the number of arguments allowed with Map.of, you don't have other choice than create an empty map and put key/value pairs one by one. Note however that, performances aren't necessarily going to be worse. You can of course reimplement your own version of Map.of with variable number of arguments.

QuentinC
  • 12,311
  • 4
  • 24
  • 37
0

Since you need something constant like, you can save those values in files and read from those files. For example save data in file in json format:

{
  "foo": "bar", 
  "test": "world", 
  "name": "david"
}

Then parse this file to a Map.

public class Main {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> map = mapper.readValue(ClassLoader.getSystemResourceAsStream("constants.json"), Map.class);
        map.forEach((k, v) -> System.out.println(k + " -> " + v));
    }
}

This example uses reading file as project resource and uses ObjectMapper to parse json to Map, but you can use any other tool for the same effect. If the data format is simple enough(string key to string value, no nested arrays, objects and such) you can save it in even simpler format and do the read, parse, add to map manually.

Chaosfire
  • 4,818
  • 4
  • 8
  • 23
  • I have 4 of these JSONs, does it mean I have to create 4 more files or can i write everything in one file? – DavidNyan10 Mar 06 '22 at 02:17
  • @DavidNyan10 If there are duplicate keys, you certainly need more than one file, otherwise you can just put them in one. If you can differentiate the contents in some logical way, it might be better to have different files, so you have an easier time later to find stuff, but that's a matter of preference. – Chaosfire Mar 06 '22 at 07:32