1

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.

Mikhail Chibel
  • 1,865
  • 1
  • 22
  • 34

2 Answers2

2

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

Hesham Ahmed
  • 207
  • 1
  • 4
2

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)
));
Andrew_CSE
  • 351
  • 2
  • 6
  • 1
    Thanks! Looks like it's `Map.ofEntries` rather than `Map.ofEntry` though. – IpsRich Jun 11 '21 at 11:58
  • Please note that this works only in [Java 9 or higher version](https://stackoverflow.com/questions/6802483/how-to-directly-initialize-a-hashmap-in-a-literal-way). – Peter Csala Jul 28 '21 at 11:57