Platinum Partner

Treating First/last Loop Iterations Differently

Sometimes, you need to iterate over a list of items and treat the first and last element differently from the rest. This tends to produce really messy code, which can be avoided using the following snippet.

Imagine you have a list of Kittens, and you want to print out a summary of them, saying "My kittens are called Bob, James, John, and Ally." You need to treat the first and last element of the list differently from the rest, lest you end up with superfluous commas in the text. You also need to deal with the cases of there being only one kitten, or no kittens at all.

To do this, you can avail yourself of a Counter class that keeps track of where you are in the iteration:

String kittenDesc = "I have no kittens.";
Counter kc = new Counter(kittens);
for (Kitten k : kittens) switch(kc.next()) {
	case one:   kittenDesc =  "My kitten is called " + k.getName() + "."; break;
	case first: kittenDesc =  "My kittens are called " + k.getName();     break;
	case item:  kittenDesc += ", " + k.getName();                         break;
	case last:  kittenDesc += " and " + k.getName() + ".";                break;
}

package com.zarkonnen.util;

import java.util.Collection;

/**
 * Used for keeping track of where you are in a collection/array being iterated over. Use by
 * initialising with the collection/array before the loop and embedding a switch on the next() Mode
 * value into the loop.
 *
 * LICENCE: This code is licenced under a BSD licence. Feel free to alter and redistribute.
 *
 * @author David Stark, http://www.zarkonnen.com
 * @version 1.0 (2007-07-11)
 */
public class Counter {
	/**
	 * An enumeration of modes identifying where in the collection/array we are.
	 */
	public enum Where {
		/** The only element of an array/collection of size 1. */ one,
		/** The first element. */                                 first,
		/** The last element of the array/collection. */          last,
		/** Any other element somewhere in the middle. */         item
	}
	
	private int size;
	private int nextIndex = 0;
	
	/**
	 * @param c A collection to keep track of. If its size changes between now and the
	 * iteration, strange things will happen.
	 */
	public Counter(Collection c) {
		size = c.size();
	}
	
	/**
	 * @param a An array to keep track of. If its size changes between now and the iteration,
	 * strange things will happen.
	 */
	public Counter(Object[] a) {
		size = a.length;
	}
	
	/**
	 * @return A Where enum value for where in the array/collection we now are:
	 * 
    *
  • one at the only element of an array/collection of size 1
  • *
  • first at the first element
  • *
  • last at the last element
  • *
  • item at any other element
  • *
*/ public Where next() { return size == 1 ? Where.one : nextIndex++ == 0 ? Where.first : nextIndex == size ? Where.last : Where.item ; } /** * @return Which index of the array/collection we're currently at. */ public int index() { return nextIndex == 0 ? 0 : nextIndex - 1; } }
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}