In other words, why do Java programmers need to create a class or explicitly create a Map when they could instead just say :
{ "name":["value1", "value2"]}
like in other languages.
In other words, why do Java programmers need to create a class or explicitly create a Map when they could instead just say :
{ "name":["value1", "value2"]}
like in other languages.
Why do Java programmers need to create a class or explicitly create a
Map
?
Because Java is a statically typed language, where everything must have its own type.
And still, the language allows you to compose a map of { "name":["value1", "value2"]}
with a single statement, using double-brace initialization:
Map<String, List<String>> map = new HashMap<String, List<String>>() {{
put("name", Arrays.asList("value1", "value2"));
}};
Map.of
& List.of
You can use new convenient literal syntax of Map.of
and List.of
, if an unmodifiable map or list works for your situation. These convenience factory methods for collections were added to Java 9 and later.
Map < String, List < String > > map = Map.of(
"nameA" , List.of( "value1" , "value2" ) ,
"nameB" , List.of( "value3" , "value4" , "value5" )
);
map.toString(): {nameA=[value1, value2], nameB=[value3, value4, value5]}
The video is about the new collection API improvements of Java 9. But in the beginning Stuart Marks explains why Java is not as convenient as other languages when it comes down to collection creation.
It's simply a limitation of the language; inline lists and maps have been proposed but as of Java 9 still won't be included in the core language.
Groovy, on the other hand, does syntax for inline lists (ArrayList
by default) and maps (LinkedHashMap
by default).