How to create a static Map of String -> Array

后端 未结 6 734
我寻月下人不归
我寻月下人不归 2021-01-11 10:51

I need to create a static Map which maps a given String to an array of int\'s.

In other words, I\'d like to define something l

6条回答
  •  别那么骄傲
    2021-01-11 11:30

    For the sake of completeness as this is the first result in google for 'java static define map' In Java 8 you can now do this.

    Collections.unmodifiableMap(Stream.of(
                new SimpleEntry<>("a", new int[]{1,2,3}),
                new SimpleEntry<>("b", new int[]{1,2,3}),
                new SimpleEntry<>("c", new int[]{1,2,3}))
                .collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue())));
    

    This nice part with this is that we aren't creating anonymous classes anymore with the double brace syntax ({{ }})

    We can then extend this with some code to clean up the pattern like this guy did here http://minborgsjavapot.blogspot.ca/2014/12/java-8-initializing-maps-in-smartest-way.html

    public static  Map.Entry entry(K key, V value) {
        return new AbstractMap.SimpleEntry<>(key, value);
    }
    
    public static  Collector, ?, Map> entriesToMap() {
        return Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue());
    }
    
    public static  Collector, ?, ConcurrentMap> entriesToConcurrentMap() {
        return Collectors.toConcurrentMap((e) -> e.getKey(), (e) -> e.getValue());
    }
    

    final result

    Collections.unmodifiableMap(Stream.of(
                entry("a", new int[]{1,2,3}),
                entry("b", new int[]{1,2,3}),
                entry("c", new int[]{1,2,3}))
                .collect(entriesToMap()));
    

    which would give us a Concurrent Unmodifiable Map.

提交回复
热议问题