How do I write this in java?
//js
const hello = {
foo: "bar",
test: "world",
name: "david"
}
i wanna 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 dont 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 wanna create a new file for that (it only has around 34 lines) and wanna keep it in the code. Also because I have 3 more like these with 20-40 keys and values in each of them, so i dont wanna create 3 extra files with just 30 lines in them. I also don't wanna 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
CodePudding user response:
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.
CodePudding user response:
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.