Different Ways to Iterate over List, Set and Map in Java

Introduction

Iteration is a common operation performed on collections such as lists, sets, and maps. Java provides multiple ways to iterate over these collections, including traditional loops, enhanced for-loops, iterators, and Java 8 features like forEach and streams. This guide covers various methods to iterate over List, Set, and Map collections, including examples using Java 8 features.

Key Points:

  • List: An ordered collection that allows duplicate elements.
  • Set: An unordered collection that does not allow duplicate elements.
  • Map: A collection that maps keys to values, with no duplicate keys allowed.

Table of Contents

  1. Iterating over List
  2. Iterating over Set
  3. Iterating over Map
  4. Conclusion

1. Iterating over List

Example List:

List<String> list = Arrays.asList("Alice", "Bob", "Charlie");

Traditional for Loop

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

Enhanced for Loop (for-each)

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

Using Iterator

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

Using ListIterator (for bidirectional iteration)

ListIterator<String> listIterator = list.listIterator();
while (listIterator.hasNext()) {
    System.out.println(listIterator.next());
}

while (listIterator.hasPrevious()) {
    System.out.println(listIterator.previous());
}

Java 8 forEach Method

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

Java 8 Stream API

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

2. Iterating over Set

Example Set:

Set<String> set = new HashSet<>(Arrays.asList("Alice", "Bob", "Charlie"));

Enhanced for Loop (for-each)

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

Using Iterator

Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

Java 8 forEach Method

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

Java 8 Stream API

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

3. Iterating over Map

Example Map:

Map<String, Integer> map = new HashMap<>();
map.put("Alice", 25);
map.put("Bob", 30);
map.put("Charlie", 35);

Iterating over Entry Set

Using for-each Loop

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

Using Iterator

Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, Integer> entry = iterator.next();
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

Iterating over Keys

Using for-each Loop

for (String key : map.keySet()) {
    System.out.println(key + ": " + map.get(key));
}

Using Iterator

Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
    String key = iterator.next();
    System.out.println(key + ": " + map.get(key));
}

Iterating over Values

Using for-each Loop

for (Integer value : map.values()) {
    System.out.println(value);
}

Using Iterator

Iterator<Integer> iterator = map.values().iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

Java 8 forEach Method

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

Java 8 Stream API

map.entrySet().stream().forEach(entry ->
    System.out.println(entry.getKey() + ": " + entry.getValue())
);

Complete Example with Output

The following program demonstrates different ways to iterate over a List, Set, and Map in Java. It includes traditional methods and Java 8 features.

import java.util.*;
import java.util.stream.Collectors;

public class CollectionIterationExample {
    public static void main(String[] args) {
        // Example List
        List<String> list = Arrays.asList("Alice", "Bob", "Charlie");

        // Example Set
        Set<String> set = new HashSet<>(Arrays.asList("Alice", "Bob", "Charlie"));

        // Example Map
        Map<String, Integer> map = new HashMap<>();
        map.put("Alice", 25);
        map.put("Bob", 30);
        map.put("Charlie", 35);

        System.out.println("Iterating over List:");
        iterateList(list);

        System.out.println("\nIterating over Set:");
        iterateSet(set);

        System.out.println("\nIterating over Map:");
        iterateMap(map);
    }

    private static void iterateList(List<String> list) {
        // Traditional for loop
        System.out.println("Using traditional for loop:");
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }

        // Enhanced for loop
        System.out.println("Using enhanced for loop:");
        for (String name : list) {
            System.out.println(name);
        }

        // Using Iterator
        System.out.println("Using Iterator:");
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        // Using ListIterator for bidirectional iteration
        System.out.println("Using ListIterator:");
        ListIterator<String> listIterator = list.listIterator();
        while (listIterator.hasNext()) {
            System.out.println(listIterator.next());
        }

        // Using Java 8 forEach method
        System.out.println("Using Java 8 forEach method:");
        list.forEach(name -> System.out.println(name));

        // Using Java 8 Stream API
        System.out.println("Using Java 8 Stream API:");
        list.stream().forEach(System.out::println);
    }

    private static void iterateSet(Set<String> set) {
        // Enhanced for loop
        System.out.println("Using enhanced for loop:");
        for (String name : set) {
            System.out.println(name);
        }

        // Using Iterator
        System.out.println("Using Iterator:");
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        // Using Java 8 forEach method
        System.out.println("Using Java 8 forEach method:");
        set.forEach(name -> System.out.println(name));

        // Using Java 8 Stream API
        System.out.println("Using Java 8 Stream API:");
        set.stream().forEach(System.out::println);
    }

    private static void iterateMap(Map<String, Integer> map) {
        // Iterating over Entry Set using for-each loop
        System.out.println("Using for-each loop over entry set:");
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        // Iterating over Entry Set using Iterator
        System.out.println("Using Iterator over entry set:");
        Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Integer> entry = iterator.next();
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        // Iterating over keys using for-each loop
        System.out.println("Using for-each loop over keys:");
        for (String key : map.keySet()) {
            System.out.println(key + ": " + map.get(key));
        }

        // Iterating over keys using Iterator
        System.out.println("Using Iterator over keys:");
        Iterator<String> keyIterator = map.keySet().iterator();
        while (keyIterator.hasNext()) {
            String key = keyIterator.next();
            System.out.println(key + ": " + map.get(key));
        }

        // Iterating over values using for-each loop
        System.out.println("Using for-each loop over values:");
        for (Integer value : map.values()) {
            System.out.println(value);
        }

        // Iterating over values using Iterator
        System.out.println("Using Iterator over values:");
        Iterator<Integer> valueIterator = map.values().iterator();
        while (valueIterator.hasNext()) {
            System.out.println(valueIterator.next());
        }

        // Using Java 8 forEach method
        System.out.println("Using Java 8 forEach method:");
        map.forEach((key, value) -> System.out.println(key + ": " + value));

        // Using Java 8 Stream API
        System.out.println("Using Java 8 Stream API:");
        map.entrySet().stream().forEach(entry ->
            System.out.println(entry.getKey() + ": " + entry.getValue())
        );
    }
}

Output

Iterating over List:
Using traditional for loop:
Alice
Bob
Charlie
Using enhanced for loop:
Alice
Bob
Charlie
Using Iterator:
Alice
Bob
Charlie
Using ListIterator:
Alice
Bob
Charlie
Using Java 8 forEach method:
Alice
Bob
Charlie
Using Java 8 Stream API:
Alice
Bob
Charlie

Iterating over Set:
Using enhanced for loop:
Alice
Charlie
Bob
Using Iterator:
Alice
Charlie
Bob
Using Java 8 forEach method:
Alice
Charlie
Bob
Using Java 8 Stream API:
Alice
Charlie
Bob

Iterating over Map:
Using for-each loop over entry set:
Alice: 25
Bob: 30
Charlie: 35
Using Iterator over entry set:
Alice: 25
Bob: 30
Charlie: 35
Using for-each loop over keys:
Alice: 25
Bob: 30
Charlie: 35
Using Iterator over keys:
Alice: 25
Bob: 30
Charlie: 35
Using for-each loop over values:
25
30
35
Using Iterator over values:
25
30
35
Using Java 8 forEach method:
Alice: 25
Bob: 30
Charlie: 35
Using Java 8 Stream API:
Alice: 25
Bob: 30
Charlie: 35

Conclusion

This program demonstrates various ways to iterate over List, Set, and Map collections in Java. It includes traditional methods, enhanced for-loops, iterators, and Java 8 features like forEach and the Stream API. By understanding these different iteration techniques, you can choose the most appropriate method for your specific use case, leading to more efficient and readable code.

Comments