Home » Php » php – Java array of objects with defined keys

php – Java array of objects with defined keys

Posted by: admin February 25, 2020 Leave a comment

Questions:

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.

How to&Answers:

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");
            }}
    );