Is there some way of initializing a Java HashMap like this?:
Map test =
new HashMap{\"test\":\"test\",\"test\
JAVA 8
In plain java 8 you also have the possibility of using Streams/Collectors
to do the job.
Map myMap = Stream.of(
new SimpleEntry<>("key1", "value1"),
new SimpleEntry<>("key2", "value2"),
new SimpleEntry<>("key3", "value3"))
.collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue));
This has the advantage of not creating an Anonymous class.
Note that the imports are:
import static java.util.stream.Collectors.toMap;
import java.util.AbstractMap.SimpleEntry;
Of course, as noted in other answers, in java 9 onwards you have simpler ways of doing the same.