以下是10道難度遞增的集合遍歷練習題,涵蓋List
、Set
、Map
的各種遍歷方式,包含解題思路、代碼實現和輸出結果:
練習題1:基礎遍歷 - ArrayList的for-each遍歷
題目:創建一個存儲5個字符串的ArrayList
(元素為"Red"、“Green”、“Blue”、“Yellow”、“Purple”),使用增強for循環(for-each)遍歷并打印所有元素。
解題思路
- 初始化
ArrayList
并添加元素。 - 使用
for-each
循環遍歷集合,直接獲取每個元素并打印。
代碼實現
import java.util.ArrayList;
import java.util.List;public class Exercise1 {public static void main(String[] args) {// 1. 初始化集合List<String> colors = new ArrayList<>();colors.add("Red");colors.add("Green");colors.add("Blue");colors.add("Yellow");colors.add("Purple");// 2. for-each遍歷System.out.println("所有顏色:");for (String color : colors) {System.out.println(color);}}
}
輸出結果
所有顏色:
Red
Green
Blue
Yellow
Purple
練習題2:索引遍歷 - ArrayList的普通for循環
題目:創建一個存儲整數的ArrayList
(元素為10、20、30、40、50),使用普通for循環(帶索引)遍歷,打印每個元素的索引和值(格式:索引x: 值y
)。
解題思路
- 初始化
ArrayList
并添加整數元素。 - 利用
size()
獲取集合長度,通過索引i
遍歷,用get(i)
獲取元素。
代碼實現
import java.util.ArrayList;
import java.util.List;public class Exercise2 {public static void main(String[] args) {// 1. 初始化集合List<Integer> numbers = new ArrayList<>();numbers.add(10);numbers.add(20);numbers.add(30);numbers.add(40);numbers.add(50);// 2. 普通for循環(帶索引)System.out.println("元素索引和值:");for (int i = 0; i < numbers.size(); i++) {System.out.println("索引" + i + ": " + numbers.get(i));}}
}
輸出結果
元素索引和值:
索引0: 10
索引1: 20
索引2: 30
索引3: 40
索引4: 50
練習題3:迭代器遍歷 - ArrayList的Iterator遍歷與刪除
題目:創建一個ArrayList
存儲字符串(元素為"Apple"、“Banana”、“Cherry”、“Banana”、“Date”),使用Iterator
遍歷,刪除所有"Banana",最后打印剩余元素。
解題思路
- 初始化
ArrayList
并添加元素(包含重復的"Banana")。 - 獲取
Iterator
對象,遍歷過程中判斷元素是否為"Banana",若是則用it.remove()
刪除。 - 遍歷結束后打印剩余元素。
代碼實現
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;public class Exercise3 {public static void main(String[] args) {// 1. 初始化集合List<String> fruits = new ArrayList<>();fruits.add("Apple");fruits.add("Banana");fruits.add("Cherry");fruits.add("Banana");fruits.add("Date");// 2. Iterator遍歷并刪除"Banana"Iterator<String> it = fruits.iterator();while (it.hasNext()) {String fruit = it.next();if ("Banana".equals(fruit)) {it.remove(); // 用迭代器刪除,避免ConcurrentModificationException}}// 3. 打印剩余元素System.out.println("刪除Banana后:" + fruits);}
}
輸出結果
刪除Banana后:[Apple, Cherry, Date]
練習題4:雙向遍歷 - LinkedList的ListIterator
題目:創建一個LinkedList
存儲字符串(元素為"First"、“Second”、“Third”、“Fourth”),使用ListIterator
先向后遍歷所有元素,再向前遍歷所有元素。
解題思路
- 初始化
LinkedList
并添加元素。 - 獲取
ListIterator
對象,用hasNext()
和next()
向后遍歷。 - 遍歷到末尾后,用
hasPrevious()
和previous()
向前遍歷。
代碼實現
import java.util.LinkedList;
import java.util.ListIterator;public class Exercise4 {public static void main(String[] args) {// 1. 初始化集合LinkedList<String> steps = new LinkedList<>();steps.add("First");steps.add("Second");steps.add("Third");steps.add("Fourth");// 2. ListIterator向后遍歷ListIterator<String> lit = steps.listIterator();System.out.println("向后遍歷:");while (lit.hasNext()) {System.out.println(lit.next());}// 3. ListIterator向前遍歷System.out.println("向前遍歷:");while (lit.hasPrevious()) {System.out.println(lit.previous());}}
}
輸出結果
向后遍歷:
First
Second
Third
Fourth
向前遍歷:
Fourth
Third
Second
First
練習題5:Set遍歷 - HashSet的for-each遍歷
題目:創建一個HashSet
存儲整數(元素為3、1、4、1、5、9、2、6),使用for-each遍歷并打印(觀察去重和無序特性)。
解題思路
- 初始化
HashSet
并添加元素(包含重復值)。 - 用for-each遍歷,打印元素(驗證
HashSet
自動去重且無序)。
代碼實現
import java.util.HashSet;
import java.util.Set;public class Exercise5 {public static void main(String[] args) {// 1. 初始化集合(含重復元素)Set<Integer> nums = new HashSet<>();nums.add(3);nums.add(1);nums.add(4);nums.add(1); // 重復元素,不會被存儲nums.add(5);nums.add(9);nums.add(2);nums.add(6);// 2. for-each遍歷System.out.println("HashSet元素(去重且無序):");for (int num : nums) {System.out.print(num + " ");}}
}
輸出結果
HashSet元素(去重且無序):
1 2 3 4 5 6 9
練習題6:有序Set遍歷 - TreeSet的遍歷與Lambda
題目:創建一個TreeSet
存儲字符串(元素為"Orange"、“Apple”、“Banana”、“Grape”),分別用for-each和Java 8的forEach
(Lambda)遍歷,觀察有序特性。
解題思路
- 初始化
TreeSet
并添加元素(字符串會按自然順序排序)。 - 先用for-each遍歷打印。
- 再用
forEach
方法結合Lambda表達式遍歷打印。
代碼實現
import java.util.TreeSet;public class Exercise6 {public static void main(String[] args) {// 1. 初始化集合TreeSet<String> fruits = new TreeSet<>();fruits.add("Orange");fruits.add("Apple");fruits.add("Banana");fruits.add("Grape");// 2. for-each遍歷(自然排序)System.out.println("for-each遍歷:");for (String fruit : fruits) {System.out.println(fruit);}// 3. Java 8 forEach(Lambda)System.out.println("Lambda遍歷:");fruits.forEach(fruit -> System.out.println(fruit));}
}
輸出結果
for-each遍歷:
Apple
Banana
Grape
Orange
Lambda遍歷:
Apple
Banana
Grape
Orange
練習題7:Map遍歷1 - HashMap的keySet遍歷
題目:創建一個HashMap
存儲學生姓名和分數(鍵值對:"Alice"→95,"Bob"→88,"Charlie"→92),使用keySet()
遍歷所有鍵,再通過鍵獲取值并打印(格式:姓名: 分數
)。
解題思路
- 初始化
HashMap
并添加鍵值對。 - 用
keySet()
獲取所有鍵的集合,遍歷鍵并通過get(key)
獲取對應值。
代碼實現
import java.util.HashMap;
import java.util.Map;
import java.util.Set;public class Exercise7 {public static void main(String[] args) {// 1. 初始化MapMap<String, Integer> studentScores = new HashMap<>();studentScores.put("Alice", 95);studentScores.put("Bob", 88);studentScores.put("Charlie", 92);// 2. keySet()遍歷Set<String> names = studentScores.keySet();System.out.println("學生分數:");for (String name : names) {int score = studentScores.get(name);System.out.println(name + ": " + score);}}
}
輸出結果
學生分數:
Alice: 95
Bob: 88
Charlie: 92
練習題8:Map遍歷2 - HashMap的entrySet遍歷
題目:使用上題的HashMap
,通過entrySet()
遍歷所有鍵值對(Map.Entry
),打印姓名和分數(效率高于keySet()
)。
解題思路
- 復用練習題7的
HashMap
。 - 用
entrySet()
獲取所有鍵值對的集合,遍歷Map.Entry
對象,直接通過getKey()
和getValue()
獲取鍵和值。
代碼實現
import java.util.HashMap;
import java.util.Map;
import java.util.Set;public class Exercise8 {public static void main(String[] args) {// 1. 初始化MapMap<String, Integer> studentScores = new HashMap<>();studentScores.put("Alice", 95);studentScores.put("Bob", 88);studentScores.put("Charlie", 92);// 2. entrySet()遍歷(推薦,效率更高)Set<Map.Entry<String, Integer>> entries = studentScores.entrySet();System.out.println("學生分數(entrySet):");for (Map.Entry<String, Integer> entry : entries) {System.out.println(entry.getKey() + ": " + entry.getValue());}}
}
輸出結果
學生分數(entrySet):
Alice: 95
Bob: 88
Charlie: 92
練習題9:有序Map遍歷 - TreeMap的遍歷與統計
題目:創建一個TreeMap
存儲商品名稱和價格(鍵值對:"筆記本"→5999,"手機"→3999,"平板"→2999),遍歷并打印所有商品,同時計算總價。
解題思路
- 初始化
TreeMap
并添加鍵值對(key
會按自然順序排序)。 - 用
entrySet()
遍歷,打印商品信息,累加價格計算總價。
代碼實現
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;public class Exercise9 {public static void main(String[] args) {// 1. 初始化TreeMapTreeMap<String, Double> products = new TreeMap<>();products.put("筆記本", 5999.0);products.put("手機", 3999.0);products.put("平板", 2999.0);// 2. 遍歷并統計總價double total = 0.0;Set<Map.Entry<String, Double>> entries = products.entrySet();System.out.println("商品列表(按名稱排序):");for (Map.Entry<String, Double> entry : entries) {String name = entry.getKey();double price = entry.getValue();System.out.println(name + ": " + price + "元");total += price;}System.out.println("總價:" + total + "元");}
}
輸出結果
商品列表(按名稱排序):
平板: 2999.0元
手機: 3999.0元
筆記本: 5999.0元
總價:12997.0元
練習題10:集合嵌套遍歷 - Map嵌套List
題目:創建一個HashMap<String, List<Integer>>
,鍵為班級名稱(“一班”、“二班”),值為該班級學生的分數列表(一班:[90, 85, 92];二班:[88, 95, 80])。遍歷該集合,打印每個班級的名稱、學生分數及平均分。
解題思路
- 初始化
HashMap
,為每個班級創建List
存儲分數并添加到Map
。 - 遍歷
Map
的entrySet()
,獲取每個班級的分數列表。 - 遍歷分數列表,打印分數并計算總和,最后計算平均分。
代碼實現
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;public class Exercise10 {public static void main(String[] args) {// 1. 初始化嵌套集合Map<String, List<Integer>> classScores = new HashMap<>();// 一班分數List<Integer> class1 = new ArrayList<>();class1.add(90);class1.add(85);class1.add(92);classScores.put("一班", class1);// 二班分數List<Integer> class2 = new ArrayList<>();class2.add(88);class2.add(95);class2.add(80);classScores.put("二班", class2);// 2. 遍歷嵌套集合Set<Map.Entry<String, List<Integer>>> entries = classScores.entrySet();for (Map.Entry<String, List<Integer>> entry : entries) {String className = entry.getKey();List<Integer> scores = entry.getValue();System.out.println("班級:" + className);System.out.print(" 分數:");int sum = 0;for (int score : scores) {System.out.print(score + " ");sum += score;}double avg = (double) sum / scores.size();System.out.println("\n 平均分:" + avg);System.out.println("-----");}}
}
輸出結果
班級:一班分數:90 85 92 平均分:89.0
-----
班級:二班分數:88 95 80 平均分:87.0
-----
難度總結
- 基礎(1-2):掌握
List
的for-each和普通for循環遍歷,理解索引的作用。 - 進階(3-4):學會
Iterator
和ListIterator
的使用,包括遍歷中刪除元素和雙向遍歷。 - 中級(5-6):熟悉
Set
的遍歷特性(去重、有序/無序),掌握Lambda遍歷方式。 - 高級(7-9):掌握
Map
的多種遍歷方式(keySet
、entrySet
),理解TreeMap
的有序性及統計功能。 - 綜合(10):能處理集合嵌套結構(
Map
嵌套List
),結合多層遍歷解決實際問題。
通過這些練習,可全面掌握Java集合的遍歷技巧及適用場景。