Iterate collection objects in java

We can iterate collection objects by following 4 ways:

  • Using Classic For Loop
  • Using Iterator Method
  • Using Enhanced For Loop
  • Using forEach Method with Lambda Expressions

Using Classic For Loop

package com.w3spoint;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * Iterate collection objects using Classic For Loop
 * @author w3spoint
 */
public class IterateCollection {
	public static void main(String[] args) {
		List<String> subjects = new ArrayList<>();
 
		subjects.add("Java");
		subjects.add("C");
		subjects.add("C++");
		subjects.add("SQL");
		subjects.add("PHP");
 
		for (int i = 0; i < subjects.size(); i++) {
		    System.out.println(subjects.get(i));
		}
	}
}

Output

Java
C
C++
SQL
PHP

Note: This method uses index approach to get the elements. This approach can not be used with all collections because Set does not support the index based approach while storing elements.

Using Iterator Method

Iterator interface have following to methods to iterate collection objects.

hasNext(): It returns true if the iteration has more elements. next(): It returns the next element in the iteration.

package com.w3spoint;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
/**
 * Iterate collection objects using Iterator
 * @author w3spoint
 */
public class IterateCollection {
	public static void main(String[] args) {
		List<String> subjects = new ArrayList<>();
 
		subjects.add("Java");
		subjects.add("C");
		subjects.add("C++");
		subjects.add("SQL");
		subjects.add("PHP");
 
		Iterator<String> iterator = subjects.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
	}
}

Output

Java
C
C++
SQL
PHP

Using Enhanced For Loop

package com.w3spoint;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * Iterate collection objects using Enhanced For Loop
 * @author w3spoint
 */
public class IterateCollection {
	public static void main(String[] args) {
		List<String> subjects = new ArrayList<>();
 
		subjects.add("Java");
		subjects.add("C");
		subjects.add("C++");
		subjects.add("SQL");
		subjects.add("PHP");
 
		for (String subject : subjects) {
		    System.out.println(subject);
		}
	}
}

Output

Java
C
C++
SQL
PHP

Using forEach Method with Lambda Expressions

package com.w3spoint;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * Iterate collection objects using forEach Method with Lambda Expressions
 * @author w3spoint
 */
public class IterateCollection {
	public static void main(String[] args) {
		List<String> subjects = new ArrayList<>();
 
		subjects.add("Java");
		subjects.add("C");
		subjects.add("C++");
		subjects.add("SQL");
		subjects.add("PHP");
 
		subjects.forEach(subject -> System.out.println(subject));
	}
}

Output

Java
C
C++
SQL
PHP
Please follow and like us:
Content Protection by DMCA.com