Reputation: 9996
I need to fill map with Iterable<Map.Entry>
. The following is an original java code:
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());
}
I have to rewrite it in groovy. Is there a concise groovy-way to do it?
Upvotes: 1
Views: 1468
Reputation: 3809
I'd use collectEntries
for that. It's similar to collect
, but it's purpose is to create a Map
.
def sourceMap = ["key1": "value1", "key2": "value2"]
Iterable<Map.Entry<String, String>> conf = sourceMap.entrySet()
def map = conf.collectEntries {
[(it.key): it.value]
}
Note the round braces around it.key
that allow you to use a variable reference as key of the newly generated Entry
.
Upvotes: 2
Reputation: 2622
In Groovy you can use the each closure instead of Iterator as follows
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
Working example here : https://groovyconsole.appspot.com/script/5100319096700928
Upvotes: 1