Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-2703

Add putEach method to Map

    XMLWordPrintableJSON

Details

    • New Feature
    • Status: Closed
    • Minor
    • Resolution: Fixed
    • 1.5.4
    • 1.6.1, 1.7.0
    • groovy-jdk
    • None

    Description

      I've frequently run across the situation where I want to create a map from two equal sized lists, using one list for the keys and a second list for the values.

      Maybe I'm missing something, but I can't seem to find a compact way to do this that doesn't require a for loop or an intermediate variable. The best I've come up with is to add this method to Map:

      Map.metaClass.putEach = { List keylist, List valuelist ->
      assert keylist.size == valuelist.size
      for (int i=0; i < keylist.size; i++)

      { delegate.put(keylist[i], valuelist[i]) }

      delegate
      }

      This allows you to just call putEach on any Map passing in two equal sized lists, e.g.:

      assert [:].putEach(['key1', 'key2', 'key3'], ['value1', 'value2', 'value3']) == ['key1':'value1', 'key2':'value2', 'key3':'value3']

      Since this seems generally useful, it might be something worth adding to the base GDK.

      Attachments

        Activity

          People

            paulk Paul King
            loverde Jim LoVerde
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: