以下是10道难度递增的集合遍历练习题,涵盖ListSetMap的各种遍历方式,包含解题思路、代码实现和输出结果:

练习题1:基础遍历 - ArrayList的for-each遍历

题目:创建一个存储5个字符串的ArrayList(元素为"Red"、"Green"、"Blue"、"Yellow"、"Purple"),使用增强for循环(for-each)遍历并打印所有元素。

解题思路

  1. 初始化ArrayList并添加元素。
  2. 使用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)。

解题思路

  1. 初始化ArrayList并添加整数元素。
  2. 利用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",最后打印剩余元素。

解题思路

  1. 初始化ArrayList并添加元素(包含重复的"Banana")。
  2. 获取Iterator对象,遍历过程中判断元素是否为"Banana",若是则用it.remove()删除。
  3. 遍历结束后打印剩余元素。

代码实现

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先向后遍历所有元素,再向前遍历所有元素。

解题思路

  1. 初始化LinkedList并添加元素。
  2. 获取ListIterator对象,用hasNext()next()向后遍历。
  3. 遍历到末尾后,用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遍历并打印(观察去重和无序特性)。

解题思路

  1. 初始化HashSet并添加元素(包含重复值)。
  2. 用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)遍历,观察有序特性。

解题思路

  1. 初始化TreeSet并添加元素(字符串会按自然顺序排序)。
  2. 先用for-each遍历打印。
  3. 再用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()遍历所有键,再通过键获取值并打印(格式:姓名: 分数)。

解题思路

  1. 初始化HashMap并添加键值对。
  2. 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())。

解题思路

  1. 复用练习题7的HashMap
  2. 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),遍历并打印所有商品,同时计算总价。

解题思路

  1. 初始化TreeMap并添加键值对(key会按自然顺序排序)。
  2. 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])。遍历该集合,打印每个班级的名称、学生分数及平均分。

解题思路

  1. 初始化HashMap,为每个班级创建List存储分数并添加到Map
  2. 遍历MapentrySet(),获取每个班级的分数列表。
  3. 遍历分数列表,打印分数并计算总和,最后计算平均分。

代码实现

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):学会IteratorListIterator的使用,包括遍历中删除元素和双向遍历。
  • 中级(5-6):熟悉Set的遍历特性(去重、有序/无序),掌握Lambda遍历方式。
  • 高级(7-9):掌握Map的多种遍历方式(keySetentrySet),理解TreeMap的有序性及统计功能。
  • 综合(10):能处理集合嵌套结构(Map嵌套List),结合多层遍历解决实际问题。

通过这些练习,可全面掌握Java集合的遍历技巧及适用场景。