What are different ways to iterate over list

What are different ways to iterate over list

Answer : List of ways are below:

  • Use for loop iterate over array
  • Use for loop iterate over collection
  • Use for loop iterate over an array or iterable
  • Use while loop iterate with iterator

Please see java code below:

package com.javahonk.iteratorenumeration;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class WaysToInterateList {

	public static void main(String[] args) {

	List<String> arrayList = new ArrayList<String>();

	arrayList.add("Java");
	arrayList.add("Honk");

	System.out.println("for loop iterate "
			+ "over array");
	for (int i = 0; i < arrayList.size(); i++) {
		System.out.println(arrayList.get(i));
	}

	System.out.println("\nfor loop iterate "
			+ "over collection");
	for (Iterator<String> iterator = 
			arrayList.iterator(); iterator.hasNext();) {
		String string = (String) iterator.next();
		System.out.println(string);

	}

	System.out.println("\nfor loop iterate "
			+ "over an array  or iterable");
	System.out.println("Preferable to "
			+ "iterate over collection");
	for (String string : arrayList) {
		System.out.println(string);
	}

	System.out.println("\nwhile loop iterate "
			+ "with iterator");
	Iterator<String> it = arrayList.iterator();
	while (it.hasNext()) {
		String string = (String) it.next();
		System.out.println(string);
	}

	}

}

 

Output:

What are different ways to iterate over list

 

Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *