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

List.withIndex()

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 2.4.0-beta-3
    • 2.4.0-rc-1
    • groovy-jdk
    • None

    Description

      A method which zips list indices is missing.

      The implementaion is this.

      public static List withIndex(List self) {
          return withIndex(self, 0);
      }
      
      public static List withIndex(List self, int offset) {
          return transpose(Arrays.asList(self, new IntRange(false, offset, offset + self.size())));
      }
      

      I can use like this.

      assert [["a", 0], ["b", 1]] == ["a", "b"].withIndex()
      assert ["1: a", "2: b"] == ["a", "b"].withIndex(1).collect { str, idx -> "$idx: $str" }
      

      In other languages the method names are like these.

      Scala: zipWithIndex()
      Kotlin: withIndices()
      Ruby: with_index(offset = 0)
      Python: enumerate(sequence, start=0)

      I chose withIndex() because there is eachWithIndex() but List.collectWithIndex() is missing and I can call it by withIndex().collect().

      Can I send a pull request to GitHub?

      Attachments

        Activity

          People

            paulk Paul King
            yukoba Yu Kobayashi
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: