This Java Collections tutorial demonstrates the different techniques to iterate over a Java Collection (List, Set and Map) using for-loop, enhanced for-loop, Iterator and Java 8 Stream.
1. Iterate through a List
The following examples show how to iterate over the items of a List in Java.
With recent coding trends, using streams allow us to iterate the list items, perform operations on items, and collect the results in a seamless manner.
List<String> list = List.of("A", "B", "C", "D");
list.stream()
//other operation as needed
.forEach(System.out::println);
Recently introduced in java 8, this method can be called on any Iterable
and takes one argument implementing the functional interface java.util.function.Consumer
.
List<String> list = List.of("A", "B", "C", "D");
list.forEach(System.out::println);
The enhanced for loop is also an excellent way to iterate over a List, and it produces readable code.
List<String> list = List.of("A", "B", "C", "D");
for(String s : list) {
System.out.println(s);
}
The Iterator returned from the List.iterator() method provides hasNext() and next() methods that can help traverse the list items in a sequential manner.
List<String> list = List.of("A", "B", "C", "D");
Iterator<String> itr = list.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
Last but the least, a traditional for-loop can also be used to traverse the list items.
List<String> list = List.of("A", "B", "C", "D");
for( int i=0; i < list.size(); i++ ) {
System.out.println(list.get(i));
}
2. Iterate through a Set
Set is very similar to List types except:
- Set does not allow duplicate elements
- Set does not provide get() method to fetch an item using the index.
So we can reuse the iteration methods of List with Set also. Only traditional for-loop cannot be used due to the unavailability of indexes-based access.
Set<String> set = Set.of("A", "B", "C", "D");
//Stream
set.stream()
//other operation as needed
.forEach(System.out::println);
//Iterable.forEach()
set.forEach(System.out::println);
//Enhanced for-loop
for(String s : set) {
System.out.println(s);
}
//Iterator
Iterator<String> itr1 = set.iterator();
while(itr1.hasNext()) {
System.out.println(itr1.next());
}
3. Iterate through a Map
The Map stores the key-value pairs. The keys are unique and each value is associated with a single key. We can iterate over the keys and values, both, in the Map.
3.1. Iterate over Keys
The Map.keySet() method returns the Set of keys in the map so we can use the methods applicable for Set for iterating over the keys in the Map.
Map<String, Integer> map = Map.of("A", 1, "B", 2, "C", 3);
//Stream
map.keySet().stream().forEach(System.out::println);
//Iterable.forEach()
map.keySet().forEach(System.out::println);
//Iterator
Iterator<String> keysItr = map.keySet().iterator();
while(keysItr.hasNext()) {
System.out.println(keysItr.next());
}
3.2. Iterate over Values
The Map.values() method returns the List of values in the map so we can use the methods applicable to the List for iterating over the keys in the Map.
Map<String, Integer> map = Map.of("A", 1, "B", 2, "C", 3);
//Stream
map.values().stream().forEach(System.out::println);
//Iterable.forEach()
map.values().forEach(System.out::println);
//Iterator
Iterator<Integer> valuesItr = map.values().iterator();
while (valuesItr.hasNext()) {
System.out.println(valuesItr.next());
}
3.3. Iterate over Entries
The Map.entrySet() method returns the Set of Map.Entry instances from the map so we can use the methods applicable to the Set for iterating over the entries in the Map.
Map<String, Integer> map = Map.of("A", 1, "B", 2, "C", 3);
//Stream
map.entrySet().stream().forEach(System.out::println);
//Iterable.forEach()
map.entrySet().forEach(System.out::println);
//Iterator
Iterator <Map.Entry<String, Integer>> entryIterator = map.entrySet().iterator();
while (entryIterator.hasNext()) {
System.out.println(entryIterator.next().getKey());
System.out.println(entryIterator.next().getValue());
}
Happy Learning !!