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

Add ability to 'slice' Map, querying multiple keys at once

    XMLWordPrintableJSON

Details

    • New Feature
    • Status: Reopened
    • Major
    • Resolution: Unresolved
    • None
    • None
    • groovy-jdk
    • None
    • Patch

    Description

      It was brought up on the dev mailing list that you could query multiple list values at once, but not multiple Map values:

      Message from groovy-dev by Jon Cox

      Groovy currently lets you say:

      def    x       =  [100,200,300,400]
      assert x[0]    == 100
      assert x[2]    == 300
      assert x[0,2]  == [100,300]
      

      You can say:

      def    y        =  [moo: 100, cow: 200, egg:300 hen:400]
      assert y["moo"] == 100
      assert y["cow"] == 300
      

      But currently, you cannot slice a Map like this:

      assert y["moo","egg"] == [100,300] 
      

      This patch adds that functionality, so you can do (from the unit test)

          void testMapSlice() {
              def m = [ a:1, b:2, c:3 ]
              
              assert m[ 'a', 'b' ] == [ 1, 2 ]
              assert m[ 'a', 'c' ] == [ 1, 3 ]
              assert m[ 'a', 'd', 'c' ] == [ 1, null, 3 ]
          }
      

      Note that the resultant List contains null for keys that were not found. This (I believe) differs from the way that Perl handles this (I believe they are just skipped in perl), but I think that having the null values gives the developer more information.

      And they could be filtered out by doing something like:

      m[ 'a', 'd', 'c' ].findAll { it }
      

      Hope it's ok!

      Attachments

        1. map_slice.diff
          2 kB
          Tim Yates
        2. slice_instead_of_getAt.diff
          2 kB
          Tim Yates

        Activity

          People

            Unassigned Unassigned
            tim_yates Tim Yates
            Votes:
            1 Vote for this issue
            Watchers:
            1 Start watching this issue

            Dates

              Created:
              Updated: