Map with Key as String and Value as List in Groovy

前端 未结 5 655
慢半拍i
慢半拍i 2021-02-03 18:54

Can anyone point me to an example of how to use a Map in Groovy which has a String as its key and a List as value?

5条回答
  •  Happy的楠姐
    2021-02-03 19:10

    One additional small piece that is helpful when dealing with maps/list as the value in a map is the withDefault(Closure) method on maps in groovy. Instead of doing the following code:

    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]
      }
    }
    

    You can do the following:

    Map m = [:].withDefault{key -> return []}
    for(object in listOfObjects)
    {
      List valueList = m.get(object.myKey)
      m.put(object.myKey, valueList)
    }
    

    With default can be used for other things as well, but I find this the most common use case for me.

    API: http://www.groovy-lang.org/gdk.html

    Map -> withDefault(Closure)

提交回复
热议问题