java

How to iterate through a list in Java

In this tutorial, we are going to see different ways to iterate through a list in Java.

  • Using List.toString()
  • Using for loop
  • Using the for-each loop
  • Using Iterator

 

Method 1: Using List.toString()

If we want to iterate over a list, we can do that by converting the list to a string using the toString() function, then displaying it:

import java.util.*;

public class Main
{
	public static void main (String[] args)
	{
		 List<String> colors = new ArrayList<String>();
		 colors.add("Blue");
		 colors.add("Red");
		 colors.add("Green");

		 System.out.println(colors.toString());
	}
}

Output:

[Blue, Red, Green]

 
[st_adsense]  

Method 2: Using for loop
import java.util.*;

public class Main
{
	public static void main (String[] args)
	{
		List<String> color = Arrays.asList("Blue", "Red", "Green");

		for (int i = 0; i < color.size(); i++) {
			System.out.println(color.get(i));
		}
	}
}

Output:

Blue
Red
Green
[st_adsense]  

Method 3: Using the for-each loop
import java.util.*;

public class Main
{
	public static void main (String[] args)
	{
		List<String> color = Arrays.asList("Blue", "Red", "Green");

		for (String str : color) {
			System.out.println(str);
		}
	}
}

Output:

Blue
Red
Green
[st_adsense]  

Method 4: Using Iterator

Iterator is an interface that is found in the “collection” framework. It allows us to iterate through a collection using the following methods:

  • hasNext(): returns true if Iterator has more items to iterate.
  • next(): it returns the next element in the collection until the hasNext() method returns true. This method throws the ‘NoSuchElementException’ exception if there is no more element.
import java.util.*;

public class Main
{
	public static void main (String[] args)
	{
		List<String> color = Arrays.asList("Blue", "Red", "Green");

		Iterator<String> i = color.iterator();
		while (i.hasNext()) {
			System.out.println(i.next());
		}
	}
}

Output:

Blue
Red
Green
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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