1

I am new in Java and I would like to write a code like PHP or Javasript or Python alowes me to write where I am able to write a literal to create an array of couples. The thing I want to achieve in PHP looks like:

$arr = [
   ['key1' => 'aaa', 'key2' => 'bbb'], 
   ['key1' => 'ccc', 'key2' => 'ddd'], 
   ['key1' => 'eee', 'key2' => 'fff']
];

It looks like it is not possible in Java. Hope it is. Thank you. Please write as simple code as possible.

1 Answer 1

2

If you are using Java version >= 9 use this way:

    List.of(
            Map.of("key1", "aaa", "key2", "bbb"),
            Map.of("key1", "ccc", "key2", "ddd"),
            Map.of("key1", "eee", "key2", "fff")
    );

For Java < 8 version:

    Arrays.asList(
            new HashMap<String, String>() {{
                put("key1", "aaa");
                put("key2", "bbb");
            }},
            new HashMap<String, String>() {{
                put("key1", "ccc");
                put("key2", "ddd");
            }},
            new HashMap<String, String>() {{
                put("key1", "eee");
                put("key2", "fff");
            }}
    );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.