java - How to initialize a map using a lambda? -
i want declare populated map field in single statement, (which may contain several nested statements,) this:
private static final map<integer,boolean> map = something-returning-an-unmodifiable-fully-populated-hashmap;
anonymous initializers won't do, same reason invoking function returns new populated map won't do: require 2 top-level statements: 1 variable declaration, , 1 method or initializer.
the double curly bracket ({{
, }}
) idiom work, creates whole new class extends hashmap<>
, , not overhead represented this.
do lambdas of java 8 perhaps offer better way of accomplishing this?
if want initialize map
in single statement, can use collectors.tomap
.
imagine want build map<integer, boolean>
mapping integer result of calling function f
:
private static final map<integer,boolean> map = collections.unmodifiablemap(intstream.range(0, 1000) .boxed() .collect(collectors.tomap(i -> i, -> f(i)))); private static final boolean f(int i) { return math.random() * 100 > i; }
if want initialize "static" known values, example in answer, can abuse stream api this:
private static final map<integer, boolean> map = stream.of(new object[] { 1, false }, new object[] { 2, true }) .collect(collectors.tomap(s -> (int) s[0], s -> (boolean) s[1]));
note real abuse , never use it: if want construct map known static values, there nothing gain using streams , better off use static initializer.
Comments
Post a Comment