[英]How can I pass a new single value map as an argument?
我有一個跟蹤主機,文件以及每個文件的各個部分的容器:
private static Map<String, Map<String, ArrayList<FileShard>>> globalFileShardMap = new HashMap<String, Map<String, ArrayList<FileShard>>>();
我想為此添加一個新條目,並且這樣做:
// filename and shard are known
ArrayList<FileShard> initShard = new ArrayList<FileShard>();
initShard.add(shard);
Map<String, ArrayList<FileShard>> initMap = new HashMap<String, ArrayList<FileShard>>();
initMap.put(filename,initShard);
globalFileShardMap.put(Node.getLocal().getHostname(), initMap);
有沒有一種方法可以將其壓縮為一行,然后將新的內部Map作為參數傳遞給globalFileShardMap.put
?
在線轉換將是-
globalFileShardMap.put(Node.getLocal().getHostname(), new HashMap<String, ArrayList<FileShard>>(){{
put(filename, new ArrayList<FileShard>(){{add(shard);}});
}});
這是一種無需創建任何匿名類就可以單行執行的方法。
globalFileShardMap.put(Node.getLocal().getHostname(),
new HashMap<>(Collections.singletonMap(filename,
new ArrayList<>(Collections.singletonList(shard)))));
這要求Java 7用於菱形<>
。
如果您實際上不需要HashMap
和ArrayList
(即需要任何舊的Map
和List
),則可以擺脫new HashMap<>
和new ArrayList<>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.