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

Iterate over the all elements excluding the last/first one

    Details

    • Type: Wish
    • Status: Closed
    • Priority: Minor
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 4.0-alpha1, 4.0
    • Component/s: Collection
    • Labels:
      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

          Activity

            People

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

              Dates

              • Created:
                Updated:
                Resolved: