Home Tutorial Java Iterator Iterator Java Order

 
 

Iterator Java Order
Posted on: November 4, 2009 at 12:00 AM
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

Related Tags for Iterator Java Order:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.