< Prev
Next >




For-Each Loop





Using for-each loop, we can iterate over the elements of any collection class that implements Iterable interface and because all the collection classes implements Iterable interface, so we can cycle through their elements using for-each loop in a very easy manner, let's see how.




Using for-each loop to iterate over a collection with String objects.


In this example we are iterating elements of ArrayList that is holding String objects using for-each loop.

import java.util.*;

class ForEachEx
{
public static void main(String... ar)
{
ArrayList<String> arr= new ArrayList<String>();

arr.add("C");
arr.add("A");
arr.add("4");
arr.add("F");
arr.add("X");
arr.add("1");



System.out.print("Iterating contents of collection using For-each : ");

for(String s : arr)		//for-each loop
{	
	System.out.print(s + " " );
}

System.out.println("\nSize of arraylist : " + arr.size());
}

}



Output is - :


Initial size of arraylist = 0
Iterating contents of collection using For-each : C A 4 F X 1
Size of arraylist : 6






Using for-each loop to iterate over a collection with Integer objects.


In this example we are iterating elements of ArrayList that is holding String objects using for-each loop.

import java.util.*;

class ForEachEx
{
public static void main(String... ar)
{
ArrayList<Integer> arr= new ArrayList<Integer>();

System.out.printl("Initial size of arraylist"+ arr.size());

arr.add(10);
arr.add(30);
arr.add(5);
arr.add(40);
arr.add(15);
arr.add(50);


System.out.print("Iterating over a collection class using for-each");
System.out.print("Elements in this collection class : ");
for(int i : arr)		//for-each loop
{	
	System.out.print(i + " " );
}

System.out.println("\nSize of arraylist : " + arr.size());
}

}


Output is - :


Initial size of arraylist = 0
Iterating over a collection using for-each
Elements in this collection class : 10 30 5 40 15 50
Size of arraylist : 6





Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter



< Prev
Next >
< ArrayDeque Class
iterator() to iterate >

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page

Notifications



Please check our latest addition

PYTHON