【问题标题】:Map with Key as String and Value as List in Groovy在 Groovy 中使用键作为字符串和值作为列表的映射
【发布时间】:2012-08-27 12:49:57
【问题描述】:

谁能给我举个例子,说明如何在 Groovy 中使用 Map,它的键是 String,值是 List

【问题讨论】:

    标签: groovy map


    【解决方案1】:

    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
    

    【讨论】:

      【解决方案2】:

      Joseph 忘记在他的示例中将值添加到withDefault。 这是我最终使用的代码:

      Map map = [:].withDefault { key -> return [] }
      listOfObjects.each { map.get(it.myKey).add(it.myValue) }
      

      【讨论】:

        【解决方案3】:

        你不需要声明 Map groovy 在内部识别它

        def personDetails = [firstName:'John', lastName:'Doe', fullName:'John Doe']
        
        // print the values..
            println "First Name: ${personDetails.firstName}"
            println "Last Name: ${personDetails.lastName}"
        

        http://grails.asia/groovy-map-tutorial

        【讨论】:

          【解决方案4】:

          在将地图/列表作为地图中的值处理时,另外一个有用的小部分是 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

          Map -> withDefault(Closure)

          【讨论】:

            【解决方案5】:
            def map = [:]
            map["stringKey"] = [1, 2, 3, 4]
            map["anotherKey"] = [55, 66, 77]
            
            assert map["anotherKey"] == [55, 66, 77] 
            

            【讨论】:

            • 还有:map.stringKey = [1, 2, 3, 4]; map.anotherKey = [55, 66, 77]
            猜你喜欢
            • 2021-10-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-01-15
            • 1970-01-01
            • 1970-01-01
            • 2013-08-15
            相关资源
            最近更新 更多