Site icon NgDeveloper

Arraylist iteration in java

Arraylist:

Arraylist is used to hold any number of elements.

Program:

[java]
package com.ngdeveloper.com;

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

public class ArrayListIteration {
public static void main(String[] args) {

// Arraylist which holds only string.
ArrayList<String> al = new ArrayList<String>();

//Adding below companies names to arraylist.
al.add("Hp");
al.add("Samsung");
al.add("Dell");
al.add("Apple");
al.add("Compaq");

//Iterator
Iterator iter = al.iterator();

//Iterating arraylist using while loop.

while(iter.hasNext()){
System.out.println("ArrayList Iteration using while loop "+iter.next());
}

//Iterating arraylist using foreach
for (String string : al) {
System.out.println("ArrayList Iteration using foreach loop "+string);
}

//Iterating arraylist using for loop.
for (String string : al) {
System.out.println("ArrayList Iteration using for loop "+string);
}
}
}
[/java]

Output:

ArrayList Iteration using while loop Hp
ArrayList Iteration using while loop Samsung
ArrayList Iteration using while loop Dell
ArrayList Iteration using while loop Apple
ArrayList Iteration using while loop Compaq
ArrayList Iteration using foreach loop Hp
ArrayList Iteration using foreach loop Samsung
ArrayList Iteration using foreach loop Dell
ArrayList Iteration using foreach loop Apple
ArrayList Iteration using foreach loop Compaq
ArrayList Iteration using for loop Hp
ArrayList Iteration using for loop Samsung
ArrayList Iteration using for loop Dell
ArrayList Iteration using for loop Apple
ArrayList Iteration using for loop Compaq

Thanks for reading this post………………!!!

Exit mobile version