<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: iterator code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sat, 26 Jul 2008 19:00:02 GMT</pubDate>
    <description>DZone Snippets: iterator code</description>
    <item>
      <title>Treating first/last loop iterations differently</title>
      <link>http://snippets.dzone.com/posts/show/4353</link>
      <description>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.&lt;br /&gt;&lt;br /&gt;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.&lt;br /&gt;&lt;br /&gt;To do this, you can avail yourself of a Counter class that keeps track of where you are in the iteration:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;String kittenDesc = "I have no kittens.";&lt;br /&gt;Counter kc = new Counter(kittens);&lt;br /&gt;for (Kitten k : kittens) switch(kc.next()) {&lt;br /&gt;	case one:   kittenDesc =  "My kitten is called " + k.getName() + "."; break;&lt;br /&gt;	case first: kittenDesc =  "My kittens are called " + k.getName();     break;&lt;br /&gt;	case item:  kittenDesc += ", " + k.getName();                         break;&lt;br /&gt;	case last:  kittenDesc += " and " + k.getName() + ".";                break;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;package com.zarkonnen.util;&lt;br /&gt;&lt;br /&gt;import java.util.Collection;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * Used for keeping track of where you are in a collection/array being iterated over. Use by&lt;br /&gt; * initialising with the collection/array before the loop and embedding a switch on the next() Mode&lt;br /&gt; * value into the loop.&lt;br /&gt; *&lt;br /&gt; * LICENCE: This code is licenced under a BSD licence. Feel free to alter and redistribute.&lt;br /&gt; *&lt;br /&gt; * @author David Stark, http://www.zarkonnen.com&lt;br /&gt; * @version 1.0 (2007-07-11)&lt;br /&gt; */&lt;br /&gt;public class Counter {&lt;br /&gt;	/**&lt;br /&gt;	 * An enumeration of modes identifying where in the collection/array we are.&lt;br /&gt;	 */&lt;br /&gt;	public enum Where {&lt;br /&gt;		/** The only element of an array/collection of size 1. */ one,&lt;br /&gt;		/** The first element. */                                 first,&lt;br /&gt;		/** The last element of the array/collection. */          last,&lt;br /&gt;		/** Any other element somewhere in the middle. */         item&lt;br /&gt;	}&lt;br /&gt;	&lt;br /&gt;	private int size;&lt;br /&gt;	private int nextIndex = 0;&lt;br /&gt;	&lt;br /&gt;	/**&lt;br /&gt;	 * @param c A collection to keep track of. If its size changes between now and the&lt;br /&gt;	 * iteration, strange things will happen.&lt;br /&gt;	 */&lt;br /&gt;	public Counter(Collection c) {&lt;br /&gt;		size = c.size();&lt;br /&gt;	}&lt;br /&gt;	&lt;br /&gt;	/**&lt;br /&gt;	 * @param a An array to keep track of. If its size changes between now and the iteration,&lt;br /&gt;	 * strange things will happen.&lt;br /&gt;	 */&lt;br /&gt;	public Counter(Object[] a) {&lt;br /&gt;		size = a.length;&lt;br /&gt;	}&lt;br /&gt;	&lt;br /&gt;	/**&lt;br /&gt;	 * @return A Where enum value for where in the array/collection we now are:&lt;br /&gt;	 * &lt;ul&gt;&lt;br /&gt;	 * &lt;li&gt;&lt;strong&gt;one&lt;/strong&gt; at the only element of an array/collection of size 1&lt;/li&gt;&lt;br /&gt;	 * &lt;li&gt;&lt;strong&gt;first&lt;/strong&gt; at the first element&lt;/li&gt;&lt;br /&gt;	 * &lt;li&gt;&lt;strong&gt;last&lt;/strong&gt; at the last element&lt;/li&gt;&lt;br /&gt;	 * &lt;li&gt;&lt;strong&gt;item&lt;/strong&gt; at any other element&lt;/li&gt;&lt;br /&gt;	 * &lt;/ul&gt;&lt;br /&gt;	 */&lt;br /&gt;	public Where next() {&lt;br /&gt;		return size == 1         ? Where.one   :&lt;br /&gt;		       nextIndex++ == 0  ? Where.first :&lt;br /&gt;		       nextIndex == size ? Where.last  :&lt;br /&gt;		                           Where.item  ;&lt;br /&gt;	}&lt;br /&gt;	&lt;br /&gt;	/**&lt;br /&gt;	 * @return Which index of the array/collection we're currently at.&lt;br /&gt;	 */&lt;br /&gt;	public int index() {&lt;br /&gt;		return nextIndex == 0 ? 0 : nextIndex - 1;&lt;br /&gt;	}&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Wed, 25 Jul 2007 10:10:01 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4353</guid>
      <author>Zarkonnen (David Stark)</author>
    </item>
    <item>
      <title> range() in Java</title>
      <link>http://snippets.dzone.com/posts/show/3867</link>
      <description>A range is a very handy feature of programing languages like Python.&lt;br /&gt;&lt;br /&gt;    * range( 10 ) -&gt; 0 1 2 3 4 5 6 7 8 9&lt;br /&gt;    * range( 5, 10 ) -&gt; 5 6 7 8 9&lt;br /&gt;    * range( 0, 10, 3 ) -&gt; 0 3 6 9&lt;br /&gt;    * range( '0', '9' ) -&gt; 012345678&lt;br /&gt;&lt;br /&gt;With an extended for loop it is possible to use such a feature too:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;/*&lt;br /&gt; * This project is made available under the terms of the BSD license, more information can be found at&lt;br /&gt; * http://www.opensource.org/licenses/bsd-license.html&lt;br /&gt; *&lt;br /&gt; * Copyright (c) 2007. Christian Ullenboom (http://www.tutego.com/) and contributors. All rights reserved.&lt;br /&gt; */&lt;br /&gt;package com.tutego;&lt;br /&gt;&lt;br /&gt;import java.util.Iterator;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * Class that generates immutable sequences (ranges) as Iterable&lt;Integer&gt;&lt;br /&gt; * objects. A range represents a start (0 if not given), an stop (mandatory) and&lt;br /&gt; * an optional step (1 by default). The start value is included in the range,&lt;br /&gt; * the stop value is exclusive. Every range is handled by an Iterable&lt;Integer&gt;&lt;br /&gt; * which can by used in an extended for loop.&lt;br /&gt; * &lt;br /&gt; * &lt;pre&gt;&lt;br /&gt; * for ( int i : range( 0, 10, 3 ) )&lt;br /&gt; *   System.out.print( i + " " ); // 0 3 6 9&lt;br /&gt; * &lt;/pre&gt;&lt;br /&gt; * &lt;br /&gt; * @author Christian Ullenboom (tutego)&lt;br /&gt; * @version 1.0&lt;br /&gt; */&lt;br /&gt;public class Range&lt;br /&gt;{&lt;br /&gt;  public static Iterable&lt;Integer&gt; range( final int start, final int stop, final int step )&lt;br /&gt;  {&lt;br /&gt;    if ( step &lt;= 0 )&lt;br /&gt;      throw new IllegalArgumentException( "step &gt; 0 isrequired!" );&lt;br /&gt;&lt;br /&gt;    return new Iterable&lt;Integer&gt;()&lt;br /&gt;    {&lt;br /&gt;      public Iterator&lt;Integer&gt; iterator()&lt;br /&gt;      {&lt;br /&gt;        return new Iterator&lt;Integer&gt;()&lt;br /&gt;        {&lt;br /&gt;          private int counter = start;&lt;br /&gt;&lt;br /&gt;          public boolean hasNext()&lt;br /&gt;          {&lt;br /&gt;            return counter &lt; stop;&lt;br /&gt;          }&lt;br /&gt;&lt;br /&gt;          public Integer next()&lt;br /&gt;          {&lt;br /&gt;            try&lt;br /&gt;            {&lt;br /&gt;              return counter;&lt;br /&gt;            }&lt;br /&gt;            finally { counter += step; }&lt;br /&gt;          }&lt;br /&gt;&lt;br /&gt;          public void remove() { }&lt;br /&gt;        };&lt;br /&gt;      }&lt;br /&gt;    };&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public static Iterable&lt;Integer&gt; range( final int start, final int stop )&lt;br /&gt;  {&lt;br /&gt;    return range( start, stop, 1 );&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public static Iterable&lt;Integer&gt; range( final int stop )&lt;br /&gt;  {&lt;br /&gt;    return range( 0, stop, 1 );&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;This is an example:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;package com.tutego;&lt;br /&gt;&lt;br /&gt;import static com.tutego.Range.range;&lt;br /&gt;&lt;br /&gt;public class RangeDemo&lt;br /&gt;{&lt;br /&gt;  public static void main( String[] args )&lt;br /&gt;  {&lt;br /&gt;    for ( int i : range( 10 ) )&lt;br /&gt;      System.out.print( i + " " );&lt;br /&gt;&lt;br /&gt;    System.out.println();&lt;br /&gt;&lt;br /&gt;    for ( int i : range( 5, 10 ) )&lt;br /&gt;      System.out.print( i + " " );&lt;br /&gt;&lt;br /&gt;    System.out.println();&lt;br /&gt;&lt;br /&gt;    for ( int i : range( 0, 10, 3 ) )&lt;br /&gt;      System.out.print( i + " " );&lt;br /&gt;&lt;br /&gt;    System.out.println();&lt;br /&gt;&lt;br /&gt;    for ( int i : range( '0', '9' ) )&lt;br /&gt;      System.out.print( (char) i  );&lt;br /&gt;&lt;br /&gt;    System.out.println();&lt;br /&gt;&lt;br /&gt;    String[] a = { "Mary", "had", "a", "little", "lamb" };&lt;br /&gt;    for ( int i : range(a.length ) )&lt;br /&gt;      System.out.printf( "%d %s%n", i, a[i] );&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 24 Apr 2007 13:20:16 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3867</guid>
      <author>tutego (Chrsitian Ullenboom)</author>
    </item>
    <item>
      <title>Handy Iterable for a range of Integers</title>
      <link>http://snippets.dzone.com/posts/show/3792</link>
      <description>Looping a specific number of times produces code a bit too verbose in Java.  The JDK5 enhanced for statement is a handy improvement, but you still have to fall back to the traditional for statement if you want to repeat a loop, say, 10 times.&lt;br /&gt;&lt;br /&gt;Not with this implementation of Iterable.  You can use it like this:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;for (int i : new Range(100))&lt;br /&gt;    System.out.printf("I have said this %d times. Read dzone.com!%n", i);&lt;br /&gt;&lt;br /&gt;class Range implements Iterable&lt;Integer&gt; {&lt;br /&gt;    &lt;br /&gt;    private final Integer stop;&lt;br /&gt;    &lt;br /&gt;    public Range(int stop) {&lt;br /&gt;        this.stop = stop;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public Iterator&lt;Integer&gt; iterator() {&lt;br /&gt;        return new Iterator&lt;Integer&gt;() {&lt;br /&gt;            &lt;br /&gt;            private Integer counter = 0;&lt;br /&gt;&lt;br /&gt;            public boolean hasNext() {&lt;br /&gt;                return (counter != stop);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            public Integer next() {&lt;br /&gt;                if (counter == stop)&lt;br /&gt;                    throw new NoSuchElementException();&lt;br /&gt;                return ++counter;&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            public void remove() {&lt;br /&gt;            }};&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 10 Apr 2007 14:39:26 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3792</guid>
      <author>asgeirn (Asgeir S. Nilsen)</author>
    </item>
    <item>
      <title>Flattening iterator</title>
      <link>http://snippets.dzone.com/posts/show/3523</link>
      <description>A trivial utility class for iterating through a collection of objects in a 'flat' manner, descending into any collections (in this case defined as iterators, iterables or arrays, rather than elements of the Collection interface ) it finds and iterating through their elements. This preserves order, so {a, b, {c, d, {e}}} will be iterated through as a, b, c, d, e.&lt;br /&gt;&lt;br /&gt;It's not very complicated, but the implementation amused me so I thought I'd share it.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;package playground.library.functional.iterator;&lt;br /&gt;&lt;br /&gt;import java.lang.reflect.Array;&lt;br /&gt;import java.util.Arrays;&lt;br /&gt;import java.util.Iterator;&lt;br /&gt;import java.util.NoSuchElementException;&lt;br /&gt;import java.util.Stack;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * An iterator that 'flattens out' collections, iterators, arrays, etc. &lt;br /&gt; *&lt;br /&gt; * That is it will iterate out their contents in order, descending into any &lt;br /&gt; * iterators, iterables or arrays provided to it.&lt;br /&gt; *&lt;br /&gt; * An example (not valid Java for brevity - some type declarations are ommitted):&lt;br /&gt; *&lt;br /&gt; * new FlattingIterator({1, 2, 3}, {{1, 2}, {3}}, new ArrayList({1, 2, 3}))&lt;br /&gt; *&lt;br /&gt; * Will iterate through the sequence 1, 2, 3, 1, 2, 3, 1, 2, 3.&lt;br /&gt; *&lt;br /&gt; * Note that this implements a non-generic version of the Iterator interface so&lt;br /&gt; * may be cast appropriately - it's very hard to give this class an appropriate &lt;br /&gt; * generic type.&lt;br /&gt; *&lt;br /&gt; * @author david&lt;br /&gt; */&lt;br /&gt;public class FlatteningIterator implements Iterator&lt;br /&gt;{&lt;br /&gt;    // Marker object. This is never exposed outside this class, so can be guaranteed&lt;br /&gt;    // to be != anything else. We use it to indicate an absense of any other object.&lt;br /&gt;    private final Object blank = new Object();&lt;br /&gt;    &lt;br /&gt;    /* This stack stores all the iterators found so far. The head of the stack is&lt;br /&gt;     * the iterator which we are currently progressing through */&lt;br /&gt;    private final Stack&lt;Iterator&lt;?&gt;&gt; iterators = new Stack&lt;Iterator&lt;?&gt;&gt;();&lt;br /&gt;    &lt;br /&gt;    // Storage field for the next element to be returned. blank when the next element&lt;br /&gt;    // is currently unknown.&lt;br /&gt;    private Object next = blank;&lt;br /&gt;        &lt;br /&gt;    public FlatteningIterator(Object... objects){&lt;br /&gt;        this.iterators.push(Arrays.asList(objects).iterator());}&lt;br /&gt;    &lt;br /&gt;    public void remove(){&lt;br /&gt;        /* Not implemented */}&lt;br /&gt;    &lt;br /&gt;    private void moveToNext(){&lt;br /&gt;        if ((next == blank) &amp;&amp; !this.iterators.empty() ) {&lt;br /&gt;            if (!iterators.peek().hasNext()){&lt;br /&gt;                iterators.pop();&lt;br /&gt;                moveToNext();}&lt;br /&gt;                else{&lt;br /&gt;                    final Object next = iterators.peek().next();&lt;br /&gt;                    if (next instanceof Iterator){&lt;br /&gt;                      iterators.push((Iterator&lt;?&gt;)next);&lt;br /&gt;                      moveToNext();}&lt;br /&gt;                    else if (next instanceof Iterable){&lt;br /&gt;                       iterators.push(((Iterable)next).iterator());&lt;br /&gt;                       moveToNext();}&lt;br /&gt;                    else if (next instanceof Array){&lt;br /&gt;                        iterators.push(Arrays.asList((Array)next).iterator());&lt;br /&gt;                        moveToNext();}&lt;br /&gt;                    else this.next = next;}}}&lt;br /&gt;    &lt;br /&gt;    /**&lt;br /&gt;     * Returns the next element in our iteration, throwing a NoSuchElementException&lt;br /&gt;     * if none is found. &lt;br /&gt;     */&lt;br /&gt;    public Object next() {&lt;br /&gt;        moveToNext();&lt;br /&gt;        &lt;br /&gt;        if (this.next == blank) throw new NoSuchElementException();&lt;br /&gt;        else{&lt;br /&gt;            Object next = this.next;&lt;br /&gt;            this.next = blank;&lt;br /&gt;            return next;&lt;br /&gt;        }}&lt;br /&gt;    &lt;br /&gt;    /**&lt;br /&gt;     * Returns if there are any objects left to iterate over. This method &lt;br /&gt;     * can change the internal state of the object when it is called, but repeated&lt;br /&gt;     * calls to it will not have any additional side effects.&lt;br /&gt;     */&lt;br /&gt;    public boolean hasNext(){&lt;br /&gt;        moveToNext();&lt;br /&gt;        return (this.next != blank);}    &lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Wed, 14 Feb 2007 19:02:51 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3523</guid>
      <author>DRMacIver (David R. MacIver)</author>
    </item>
    <item>
      <title>Iterator to return N items at-a-time</title>
      <link>http://snippets.dzone.com/posts/show/714</link>
      <description>Copied from paul cannon's recipe &lt;a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439095&gt;here&lt;/a&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;def group(iterator, count):&lt;br /&gt;    itr = iter(iterator)&lt;br /&gt;    while True:&lt;br /&gt;        yield tuple([itr.next() for i in range(count)])&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;After the above definition, you can use it very easily.&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&gt;&gt;&gt; list(group([0, 1, 2, 3, 4, 5], 2))&lt;br /&gt;[(0, 1), (2, 3), (4, 5)]&lt;br /&gt;&lt;br /&gt;&gt;&gt;&gt; dataset = ['Nausori', 5, 'Namadi', 10, 'Suva', 3]&lt;br /&gt;&gt;&gt;&gt; for place, value in group(dataset, 2):&lt;br /&gt;...   print '%s: %s' % (place, value)&lt;br /&gt;... &lt;br /&gt;Nausori: 5&lt;br /&gt;Namadi: 10&lt;br /&gt;Suva: 3&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;The above code is somewhat simplified. &lt;br /&gt;See the &lt;a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439095&gt;recipe&lt;/a&gt; for full discussion.</description>
      <pubDate>Thu, 15 Sep 2005 00:46:50 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/714</guid>
      <author>korakot (Korakot Chaovavanich)</author>
    </item>
  </channel>
</rss>
