Uploaded image for project: 'Commons Collections'
  1. Commons Collections
  2. COLLECTIONS-450

Iterate over the all elements excluding the last/first one

    XMLWordPrintableJSON

Details

    • Wish
    • Status: Closed
    • Minor
    • Resolution: Fixed
    • None
    • 4.0-alpha1, 4.0
    • Collection
    • None

    Description

      The Problem
      ============
      In many applications you will extremly often find this sort of code:
      int i=0;
      for (element:elements)
      {
      i++;
      if (i!=elemets.size)

      { processLastElement(element); }

      else

      { // Just for last element processLastElement(element); }

      }
      It happens often, if not just all collections's elements themself must be processed, but some actions must be performed on going from one element to the next. Since the last element has no successor, this actions must be skipped when processing the last element. A very famous example is, if your are going the generate a comma-separated-vector from a Collection<String>: You will end up in a code like above.

      Proposal
      =========
      The method <T>CollectionUtils.forAllButLastDo(Collection<T>, C)
      should be introduced, which process all elements of a collection, but skips the last one, which will be just returned. The above code can be then re-written:

      processLastElement(forAllButLastDo(elements,
      new Closure<T>{
      execute(T element)

      { processAllButTheLast(element) }

      }
      ))

      Attachments

        1. patch_COLLECTIONS-450.txt
          10 kB
          J. Moldawski

        Activity

          People

            Unassigned Unassigned
            yevgen.moldawski@capgemini.com J. Moldawski
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: