Programming / Java

Iterating through Data Collections in Java

by Libz
03 Jun 2016 at 12:31hrs | 2266 Views
In this short tutorial we will be looping through collections in Java using  iterator and for-each.


import java.util.*;

public class Main {

public static void main(String[] args) {
System.out.println("Cities in Zimbabwe");

//Create an ArrayList called 'cityList'
List<String> cityList = new ArrayList<>();

//Add cities to cityList using add() method
cityList.add("Bulawayo");
cityList.add("Gweru");
cityList.add("Harare");
cityList.add("Mutare");

System.out.println("===== Cities Array");

//Print the array cityList
System.out.println(cityList);

System.out.println("===== Iterator");

//Iterator
Iterator<String> myList = cityList.iterator();

while(myList.hasNext()){
System.out.println(myList.next());
}
System.out.println("===== for-each");

//For-each

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

}
}

Results


Cities in Zimbabwe
===== Cities Array
[Bulawayo, Gweru, Harare, Mutare]
===== Iterator
Bulawayo
Gweru
Harare
Mutare
===== for-each
Bulawayo
Gweru
Harare
Mutare


Source - a{C}



Chat Login

Register | Forgot password