Share on Google+Share on Google+

Iterator Java Order

Advertisement
In this section of tutorial we will learn how to use the use Ordered collection with the Iterator interface. We will create an example to display the contents of the ArrayList and Set Collection using Iterator.

  • List collection elements are ordered while set elements are unordered.
  • The iterator() method of the List Interface gives elements in propersequence.
  • The iterator() method of the Set Interface gives elements inimproper sequence.


Java Order Iterator Example
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class order {
	public static void main(String[] args) {

		String ar1[] = { "list", "array", "queue", "map", "collections" };

		List list = new ArrayList();
		Set set = new HashSet();
		for (String object : ar1) {
			list.add(object);
			set.add(object);
		}
		Iterator listit = list.iterator();
		Iterator setit = set.iterator();
		System.out.println("List elemenys are ordered--->");
		while (listit.hasNext()) {
			System.out.print(listit.next() + "\t");
		}

		System.out.println("\nSet  elements are Unordered--->");
		while (setit.hasNext()) {
			System.out.print(setit.next() + "\t");
		}
	}

}

Output

List elemenys are ordered---> list array queue map collections Set elements are Unordered---> queue map list collections array

Advertisements

Posted on: November 4, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.