从地图条目初始化Map <string,object =“”>实例

时间:2019-02-04 05:32:38

标签: java hashmap java-10

说我有一些这样的地图条目:

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

我收到此错误:

  

无法解析方法   'of(java.util.Map.Entry,   java.util.Map.Entry,   java.util.Map.Entry)'

我只想从地图中的条目创建一个新地图,我该怎么做? 问题不是专门针对如何在给定Map.Entry实例的情况下初始化Map。

5 个答案:

答案 0 :(得分:13)

替换

Map.of(a,b,c); 

Map.ofEntries(a,b,c);

如果您仍要使用Map.of(),则应明确粘贴键和值。

  

Map.Entry()返回包含给定值的不可变Map.Entry   关键和价值。这些条目适用于填充Map实例   使用Map.ofEntries()方法。

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

答案 1 :(得分:3)

在jdk-9中,您可以使用from concurrent.futures import ProcessPoolExecutor, wait from pathlib import Path import sys def translate(filename): print(filename) with open(filename, "r") as f, open(filename + ".x", , "w") as g: for line in f: g.write(line) def main(path_to_file_with_list): futures = [] with ProcessPoolExecutor(max_workers=8) as executor: for filename in Path(path_to_file_with_list).open(): futures.append(executor.submit(translate, "filelist/" + filename)) wait(futures) #simplify waiting on processes if you don't need the result. for future in futures: if future.excpetion() is not None: raise future.exception() #ProcessPoolEcecutors swallow exceptions without telling you... print("done") if __name__ == "__main__": main(sys.argv[1]) 用键值对创建Map.of()

Map

也可以使用Map<String, Object> map = Map.of("a", new Object(), "b", new Object(), "c", new Object());

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())); OP建议

答案 2 :(得分:2)

简单的答案是:

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

如果您想知道,Map.entry(key,val)的类型为Map.Entry<K,V>

答案 3 :(得分:2)

使用此

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

代替

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

答案 4 :(得分:2)

要根据条目创建地图,请使用以下任一方法:

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);

或:

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

您也可以创建地图而无需显式创建条目:

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