Reputation: 1955
What is the shortest way to initialise a Properties object with values, to substitute the code below?
Properties properties = new Properties();
properties.put("key1", "value1");
properties.put("key2", "value2");
properties.put("key3", "value3");
I come across this question while creating unit tests, so the code doesn't need to handle many entries, 3-5 is enough. Loading from the file is a good solution for many use cases but want some easy to use solution which requre minimal effort.
Upvotes: 2
Views: 8272
Reputation: 359
I realize this is an old post, but it came up for me in a search while I was looking for something else, so I thought that if it came up for me, it may come up for someone else that's actually looking for it. As a previous poster said, Java is a verbose language, but there are ways to make it less so without reducing comprehensibility or increasing complexity. This isn't quite a "one-liner" but it's fairly easy to read/understand.
import java.util.Map;
import static java.util.Map.entry;
...
Properties props = new Properties();
props.putAll(Map.ofEntries(
entry("key1", value1),
entry("key2", value2),
entry("key3", value3)
));
Upvotes: 3
Reputation: 207
While I think the properties.put method you have in your question requires minimal effort, you can use the following if that seems easier (we use it for cases where we're pasting key=value pairs from some files, intellij adds the \n when pasting multiple lines)
Properties properties = new Properties();
properties.load(new ByteArrayInputStream("key1=value1\nkey2=value2\nkey3=value3".getBytes(StandardCharsets.ISO_8859_1)));
Edit using Charset ISO_8859, thanks to dnault for pointing it out
Upvotes: 2