How can I initialise a static Map?

前端 未结 30 1745
慢半拍i
慢半拍i 2020-11-22 08:43

How would you initialise a static Map in Java?

Method one: static initialiser
Method two: instance initialiser (anonymous subclass) or some other m

30条回答
  •  感动是毒
    2020-11-22 09:34

    Well... I like enums ;)

    enum MyEnum {
        ONE   (1, "one"),
        TWO   (2, "two"),
        THREE (3, "three");
    
        int value;
        String name;
    
        MyEnum(int value, String name) {
            this.value = value;
            this.name = name;
        }
    
        static final Map MAP = Stream.of( values() )
                .collect( Collectors.toMap( e -> e.value, e -> e.name ) );
    }
    

提交回复
热议问题