[英]Map with Key as String and Value as List in Groovy
誰能指出一個示例,說明如何在Groovy中使用以String
為鍵, List
為值的Map
?
Groovy幾乎接受所有Java語法,因此有很多選擇,如下所示:
// Java syntax
Map<String,List> map1 = new HashMap<>();
List list1 = new ArrayList();
list1.add("hello");
map1.put("abc", list1);
assert map1.get("abc") == list1;
// slightly less Java-esque
def map2 = new HashMap<String,List>()
def list2 = new ArrayList()
list2.add("hello")
map2.put("abc", list2)
assert map2.get("abc") == list2
// typical Groovy
def map3 = [:]
def list3 = []
list3 << "hello"
map3.'abc'= list3
assert map3.'abc' == list3
def map = [:]
map["stringKey"] = [1, 2, 3, 4]
map["anotherKey"] = [55, 66, 77]
assert map["anotherKey"] == [55, 66, 77]
groovy中的地圖上的withDefault(Closure)
方法是在處理地圖/列表中的值時另一個有用的小片段。 而不是執行以下代碼:
Map m = [:]
for(object in listOfObjects)
{
if(m.containsKey(object.myKey))
{
m.get(object.myKey).add(object.myValue)
}
else
{
m.put(object.myKey, [object.myValue]
}
}
您可以執行以下操作:
Map m = [:].withDefault{key -> return []}
for(object in listOfObjects)
{
List valueList = m.get(object.myKey)
m.put(object.myKey, valueList)
}
默認情況下,它也可以用於其他用途,但是我發現這是我最常用的用例。
API: http : //www.groovy-lang.org/gdk.html
映射-> withDefault(Closure)
您無需內部聲明Map groovy就可以識別它
def personDetails = [firstName:'John', lastName:'Doe', fullName:'John Doe']
// print the values..
println "First Name: ${personDetails.firstName}"
println "Last Name: ${personDetails.lastName}"
約瑟夫(Joseph)忘記了在示例中使用withDefault
添加值。 這是我最終使用的代碼:
Map map = [:].withDefault { key -> return [] }
listOfObjects.each { map.get(it.myKey).add(it.myValue) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.