簡體   English   中英

從Iterable創建一個地圖 <Map.Entry> 在groovy

[英]Create a map from an Iterable<Map.Entry> in groovy

我需要用Iterable<Map.Entry>填充地圖。 以下是原始java代碼:

Iterable<Map.Entry<String, String>> conf;
Iterator<Map.Entry<String, String>> itr = conf.iterator();
Map<String, String> map = new HashMap<String, String>();
while (itr.hasNext()) {
    Entry<String, String> kv = itr.next();
    map.put(kv.getKey(), kv.getValue());
}

我必須在groovy中重寫它。 有一個簡潔的groovy方式來做到這一點?

我會使用collectEntries 它與collect類似,但它的目的是創建一個Map

def sourceMap = ["key1": "value1", "key2": "value2"]
Iterable<Map.Entry<String, String>> conf = sourceMap.entrySet()

def map = conf.collectEntries {
    [(it.key): it.value]
}

請注意it.key周圍的it.key ,它允許您使用變量引用作為新生成的Entry鍵。

在Groovy中,您可以使用每個閉包而不是Iterator ,如下所示

Map<Map.Entry<String, String>> sourceMap = ["key1" : "value1", "key2" : "value2"]
Map<Map.Entry<String, String>> targetMap = [:]
sourceMap.each{ key, value ->
targetMap[key] = value
}

println ​targetMap

這里的工作示例: https//groovyconsole.appspot.com/script/5100319096700928

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM