[Java] Traversing a Java collection : For vs Foreach vs Stream Foreach vs Stream ForeachOrdered - Coded Java

Latest

Quality & Simple Java Content

Sep 23, 2018

[Java] Traversing a Java collection : For vs Foreach vs Stream Foreach vs Stream ForeachOrdered

Traversing a Java collection


First We create a list of String objects,

List<String> list = new ArrayList<>();

list.add("DEF");
list.add("ABC");
list.add("GHI");
     

For Loop

 for(int i=0; i < list.size() ; i++){
    System.out.println( list.get(i) );
 }


For Each 

for(String value : list){
    System.out.println( value );
}


Stream ForEach

list.stream().forEach(System.out::println);


Stream ForEachOrdered

list.stream().forEachOrdered(System.out::println);


Note : All of these traversing is not Null safe, NullPointerException would be thrown if the list in Null.

....

No comments:

Post a Comment