Iterating over Collections in Java: Examples

In this tutorial, I am going to share with you a few different techniques you can use to iterate over a collection in Java.

Iterating ArrayList with Enhanced For-Loop

 List<String> names = new ArrayList<>();
 names.add("Sergey");
 names.add("Bill");
 names.add("John");

for(String name: names)
{
    System.out.println(name);
}

Output:

Sergey
Bill
John

We declare a List of String objects named names using the ArrayList implementation. We then add three String objects to the list using the add() method. The for loop iterates through each element in the names list using the enhanced for loop (also known as the for-each loop) and assigns each element to a variable named name of type String. Finally, we print each name variable to the console using the println() method of the System.out object.

Iterating ArrayList with forEach() and Lambda

List<String> names = new ArrayList<>();
names.add("Sergey");
names.add("Bill");
names.add("John");

names.forEach(name -> System.out.println(name));

The forEach() method of the names list is called with a lambda expression as an argument. The lambda expression takes a name parameter, which represents each element in the list. The System.out.println(name) statement is executed for each element in the list, printing each name to the console.

forEach, Stream, Filter and Lamda

List<String> names = new ArrayList<>();
names.add("Sergey");
names.add("Bill");
names.add("John");

names.stream().filter(s->s.contains("S")).forEach(name -> System.out.println(name));
       

Output:

Sergey

The stream() method of the names list is called to convert the list into a stream, and the filter() method is called on the stream to select only the elements that contain the letter “S” in them.

The forEach() method is then called on the resulting stream, which executes a lambda expression for each element that meets the condition specified in the filter() method. The lambda expression takes a name parameter, which represents each selected element in the stream, and prints each name to the console using the System.out.println(name) statement.

Iterating ArrayList Using Iterator

 List<String> names = new ArrayList<>();
 names.add("Sergey");
 names.add("Bill");
 names.add("John");
 
 Iterator iter = names.iterator();
 while(iter.hasNext())
 {
    System.out.println(iter.next());
 }

Output:

Sergey
Bill
John

An iterator object is created using the iterator() method of the names list. The while loop iterates through each element in the names list using the hasNext() and next() methods of the iterator.

The hasNext() method checks if there is another element in the list, and if there is, the next() method returns that element. The System.out.println() statement is executed for each element returned by the iterator, printing each name to the console.

Iterating Over HashMap with Enhanced For-Loop

Map<String, String> keyValues = new HashMap<>();
keyValues.put("firstName", "Sergey");
keyValues.put("lastName", "Kargopolov");
keyValues.put("country", "Canada");

for (Map.Entry<String, String> entry : keyValues.entrySet()) {
 System.out.println(entry.getKey() + " : " + entry.getValue());
}

Output:

firstName : Sergey
lastName : Kargopolov
country : Canada

This code declares a Map of String keys and String values named keyValues using the HashMap implementation. It then adds three key-value pairs to the map using the put() method.

The for loop iterates through each entry in the keyValues map using the entrySet() method, which returns a Set of key-value pairs. For each entry, the key and value are obtained using the getKey() and getValue() methods of the Map.Entry interface.

The System.out.println() statement is executed for each entry, printing the key and value to the console in the format “key : value”.

Iterating Over HashMap with forEach() and Lambda

Map<String, String> keyValues = new HashMap<>();
keyValues.put("firstName", "Sergey");
keyValues.put("lastName", "Kargopolov");
keyValues.put("country", "Canada");

keyValues.forEach((key,value)->System.out.println(key + " : " + value));

The forEach() method is called on the keyValues map, which accepts a lambda expression as an argument. The lambda expression takes a key and value parameter, which represent each key-value pair in the map, and prints them to the console using the System.out.println() statement in the format “key : value”.

Iterating Over HashMap Using EntrySet

Map<String, String> keyValues = new HashMap<>();
keyValues.put("firstName", "Sergey");
keyValues.put("lastName", "Kargopolov");
keyValues.put("country", "Canada");
       
keyValues.entrySet().forEach(entry -> System.out.println(entry.getKey() + " : " + entry.getValue()));
  

The entrySet() method is called on the keyValues map, which returns a Set of key-value pairs in the map. The forEach() method is then called on the Set, which accepts a lambda expression as an argument.

The lambda expression takes a single parameter named entry, which represents each key-value pair in the map, and prints them to the console using the System.out.println() statement in the format “key : value”.

I hope this short Java tutorial with code examples on how to iterate over a List and Map in Java was helpful for you.

If you are learning Java and enjoy learning by watching a series of step-by-step video lessons, then take a look at the list of video courses below. One of them might help you speed up your learning progress.

Leave a Reply

Your email address will not be published. Required fields are marked *