Can we iterate through collection using for loop?

Answers were Sorted based on User's Feedback



Can we iterate through collection using for loop?..

Answer / qim2010

Yes.


/*
Iterate through a Collection using Java Iterator Example

This Java Example shows how to iterate through a Collection
using Java Iterator.

*/
import java.util.Iterator;
import java.util.ArrayList;

public class JavaIteratorExample {
public static void main(String[] args) {
//create an ArrayList object
ArrayList aList = new ArrayList();

//populate ArrayList object
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");

/*
Get Iterator object by invoking iterator method of
collection.
Iterator provides hasNext() method which returns
true if has more
elements. next() method returns the element in
iteration.
*/

//iterate through the ArrayList values using
Iterator's hasNext and next methods
for (Iterator itr = aList.iterator(); itr.hasNext();) {
//while(itr.hasNext())
System.out.println(itr.next());
/*
Please note that next method may throw a
java.util.NoSuchElementException
if iteration has no more elements.
*/
}
}
}

Is This Answer Correct ?    3 Yes 0 No

Can we iterate through collection using for loop?..

Answer / haneef

Yes, We can

Set set=new HashSet();
set.add("one");
set.add("two");

for(Iterator it=set.iterator();it.hasNext();)
{
System.out.println(it.next());
}

Is This Answer Correct ?    3 Yes 1 No

Post New Answer

More Core Java Interview Questions

How use .contains in java?

0 Answers  


What is a ternary operator in java? What is an interface?

0 Answers  


What is the difference between abstract class and interface?

3 Answers   Aspire,


What are functions in java?

0 Answers  


can java object be locked down for exclusive use by a given thread? Or what happens when a thread cannot acquire a lock on an object? : Java thread

0 Answers  






Are variables stored in ram?

0 Answers  


Write the program numbers into words.For example 2345==two thousand three hundred fourty five

2 Answers   TCS,


Why is java not 100% pure oops?

0 Answers  


What is multi level inheritance in java?

0 Answers  


How many types of operators are there?

0 Answers  


Q) I have a ArrayList object, in that object i have added 5 integer values, 5 float values, 5 string values. Now question is how can delete particular type of data ( i.e all int values or all float values or string values) in that list object at a time?

3 Answers   Aricent,


how can you catch multiple exceptions in java?

0 Answers   Cyient,


Categories