Java Foreach Loop: Iterate Collections Easily

In Java, iterating through a collection using foreach can be achieved by the following method:

List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");

// 使用foreach遍历List集合
for(String element : list) {
    System.out.println(element);
}

Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);

// 使用foreach遍历Set集合
for(Integer element : set) {
    System.out.println(element);
}

Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

// 使用foreach遍历Map集合
for(Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}

The above code demonstrates how to use a foreach loop to iterate through elements in a List, Set, and Map collection. When iterating through a Map collection, it is necessary to use the entrySet() method to obtain a set of key-value pairs, and then iterate through them using foreach.

bannerAds