Map with Key as String and Value as List in Groovy

前端 未结 5 603
慢半拍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条回答
  • 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)

    0 讨论(0)
  • 2021-02-03 19:18

    you don't need to declare Map groovy internally recognizes it

    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

    0 讨论(0)
  • 2021-02-03 19:20

    Groovy accepts nearly all Java syntax, so there is a spectrum of choices, as illustrated below:

    // 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
    
    0 讨论(0)
  • 2021-02-03 19:30
    def map = [:]
    map["stringKey"] = [1, 2, 3, 4]
    map["anotherKey"] = [55, 66, 77]
    
    assert map["anotherKey"] == [55, 66, 77] 
    
    0 讨论(0)
  • 2021-02-03 19:31

    Joseph forgot to add the value in his example with withDefault. Here is the code I ended up using:

    Map map = [:].withDefault { key -> return [] }
    listOfObjects.each { map.get(it.myKey).add(it.myValue) }
    
    0 讨论(0)
提交回复
热议问题