How can I initialise a static Map?

前端 未结 30 1052
慢半拍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:43

    Java 9

    We can use Map.ofEntries, calling Map.entry( k , v ) to create each entry.

    import static java.util.Map.entry;
    private static final Map map = Map.ofEntries(
            entry(1, "one"),
            entry(2, "two"),
            entry(3, "three"),
            entry(4, "four"),
            entry(5, "five"),
            entry(6, "six"),
            entry(7, "seven"),
            entry(8, "eight"),
            entry(9, "nine"),
            entry(10, "ten"));
    

    We can also use Map.of as suggested by Tagir in his answer here but we cannot have more than 10 entries using Map.of.

    Java 8 (Neat Solution)

    We can create a Stream of map entries. We already have two implementations of Entry in java.util.AbstractMap which are SimpleEntry and SimpleImmutableEntry. For this example we can make use of former as:

    import java.util.AbstractMap.*;
    private static final Map myMap = Stream.of(
                new SimpleEntry<>(1, "one"),
                new SimpleEntry<>(2, "two"),
                new SimpleEntry<>(3, "three"),
                new SimpleEntry<>(4, "four"),
                new SimpleEntry<>(5, "five"),
                new SimpleEntry<>(6, "six"),
                new SimpleEntry<>(7, "seven"),
                new SimpleEntry<>(8, "eight"),
                new SimpleEntry<>(9, "nine"),
                new SimpleEntry<>(10, "ten"))
                .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue));
    

提交回复
热议问题