[jira] [Commented] (COLLECTIONS-450) Iterate over the all elements excluding the last/first one

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

[jira] [Commented] (COLLECTIONS-450) Iterate over the all elements excluding the last/first one

AD_LB (Jira)

    [ https://issues.apache.org/jira/browse/COLLECTIONS-450?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=13634483#comment-13634483 ]

Thomas Neidhart commented on COLLECTIONS-450:

A collection provides an iterator over its elements, thus the notion of "first" or "last" element is derived from the iteration order.

> Iterate over the all elements excluding the last/first one
> ----------------------------------------------------------
>                 Key: COLLECTIONS-450
>                 URL: https://issues.apache.org/jira/browse/COLLECTIONS-450
>             Project: Commons Collections
>          Issue Type: Wish
>          Components: Collection
>            Reporter: J. Moldawski
>            Priority: Minor
>         Attachments: patch_COLLECTIONS-450.txt
> 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)
>       }
>    }
>   ))

This message is automatically generated by JIRA.
If you think it was sent incorrectly, please contact your JIRA administrators
For more information on JIRA, see: http://www.atlassian.com/software/jira