简体   繁体   中英

Initialize Map<String, Object> instance from Map entries

Say I have some map entries like so:

var a = Map.entry("a", new Object());
var b = Map.entry("b", new Object());
var c = Map.entry("c", new Object());

var m = Map.of(a,b,c);  // error here

I get this error:

Cannot resolve method 'of(java.util.Map.Entry, java.util.Map.Entry, java.util.Map.Entry)'

I just want to make a new Map from entries in a map, how can I do this? Not the question is specifically about how to init a Map given Map.Entry instances.

Replace

Map.of(a,b,c); 

with

Map.ofEntries(a,b,c);

If you want to still use Map.of() then you shall paste keys and values explicitly.

Map.Entry() returns an immutable Map.Entry containing the given key and value. These entries are suitable for populating Map instances using the Map.ofEntries() method.

When to use Map.of() and when to use Map.ofEntries()

From jdk-9 you can use Map.of() to create Map with key value pairs

Map<String, Object> map = Map.of("a", new Object(), "b", new Object(), "c", new Object());

And also by using SimpleEntry

Map<String, Object> map = Map.ofEntries(
  new AbstractMap.SimpleEntry<>("a", new Object()),
  new AbstractMap.SimpleEntry<>("b", new Object()),
  new AbstractMap.SimpleEntry<>("c", new Object()));

Or by using Map.ofEntries OP suggestion

The simple answer is:

var a = Map.entry("a", new Object());
var b = Map.entry("b", new Object());
var c = Map.entry("c", new Object());

var m = Map.ofEntries(a,b,c);  // ! use Map.ofEntries not Map.of

And the type of Map.entry(key,val) is Map.Entry<K,V> , in case you were wondering.

Use this

var m = Map.ofEntries(a, b, c);

instead of

var m = Map.of(a,b,c);

To create a map from entries Use either:

var a = Map.entry("a", new Object());
var b = Map.entry("b", new Object());
var c = Map.entry("c", new Object());

var m = Map.ofEntries(a,b,c);

or:

var m = Map.ofEntries(
             entry("a", new Object()),
             entry("b", new Object()),
             entry("c", new Object()));

You can also create the map without explicitly creating the entries:

var m = Map.of("a", new Object(),
               "b", new Object(),
               "c", new Object());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM