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
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.