How to directly initialize a HashMap (in a literal way)?

后端 未结 14 2514
野趣味
野趣味 2020-11-22 10:58

Is there some way of initializing a Java HashMap like this?:

Map test = 
    new HashMap{\"test\":\"test\",\"test\         


        
14条回答
  •  悲&欢浪女
    2020-11-22 11:29

    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.

提交回复
热议问题