//How to iterate List in java?
There are Many Ways :-----------
package
collectctiondemo;
import
java.util.ArrayList;
import
java.util.Iterator;
import
java.util.List;
public class
ListIterateDemo {
public static void
main(String[] args) {
List<String> l=new
ArrayList<>();
l.add("govind");
l.add("ballabh");
l.add("khan");
l.add("java");
l.add("technology");
System.out.println("iterate
using for loop----ist way");
for(int i=0;i<l.size();i++)
{
System.out.println(l.get(i));
}
System.out.println("iterate
using for each loop----2nd way");
for(String
s1:l)
{
System.out.println(s1);
}
System.out.println("iterate
using while loop----3rd way");
int i=0;
while( i<l.size())
{
System.out.println(l.get(i));
i++;
}
System.out.println("iterate
using iterator----4th way");
Iterator<String>
it1 = l.iterator();
while (it1.hasNext())
{
String s1
= it1.next();
System.out.println(s1);
}
System.out.println("iterate
using collection stream() java 8 concept----5th way");
l.forEach((temp)->
{
System.out.println(temp);
});
System.out.println("iterate
using for loop with iterator----6th way");
for(Iterator<String>
it = l.iterator();it.hasNext();)
{
System.out.println(it.next());
}
}
}
o/p:-------------------
iterate using for loop----ist way
govind
ballabh
khan
java
technology
iterate using for each loop----2nd way
govind
ballabh
khan
java
technology
iterate using while loop----3rd way
govind
ballabh
khan
java
technology
iterate using iterator----4th way
govind
ballabh
khan
java
technology
iterate using collection stream() java
8 concept----5th way
govind
ballabh
khan
java
technology
iterate using for loop with
iterator----6th way
govind
ballabh
khan
java
technology
No comments:
Post a Comment