以下是4道难度递增的Java集合框架练习题,涵盖List、Set、Map的核心用法,包含解题思路、完整代码和输出结果:
练习题1:基础难度 - ArrayList 操作
题目:使用ArrayList
完成以下操作:
- 创建一个存储字符串的
ArrayList
,添加5个元素(如"Apple"、“Banana”、“Cherry”、“Date”、“Elderberry”)。 - 遍历集合并打印所有元素。
- 删除索引为2的元素,替换索引为1的元素为"Blueberry"。
- 查找"Date"是否在集合中,若存在则输出其索引。
- 清空集合并判断是否为空。
解题思路
- 使用
ArrayList
的add()
方法添加元素。 - 用增强for循环遍历集合。
- 用
remove(int index)
删除指定索引元素,set(int index, E element)
替换元素。 - 用
contains(Object o)
判断元素是否存在,indexOf(Object o)
获取索引。 - 用
clear()
清空集合,isEmpty()
判断是否为空。
代码实现
import java.util.ArrayList;
import java.util.List;
public class ArrayListExercise {
public static void main(String[] args) {
// 1. 创建集合并添加元素
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Date");
fruits.add("Elderberry");
// 2. 遍历并打印所有元素
System.out.println("初始集合元素:");
for (String fruit : fruits) {
System.out.print(fruit + " ");
}
System.out.println("\n-----");
// 3. 删除索引为2的元素,替换索引为1的元素
fruits.remove(2); // 删除"Cherry"
fruits.set(1, "Blueberry"); // 替换"Banana"为"Blueberry"
System.out.println("修改后集合元素:");
for (String fruit : fruits) {
System.out.print(fruit + " ");
}
System.out.println("\n-----");
// 4. 查找"Date"是否存在及其索引
String target = "Date";
if (fruits.contains(target)) {
System.out.println(target + " 存在,索引为:" + fruits.indexOf(target));
} else {
System.out.println(target + " 不存在");
}
System.out.println("-----");
// 5. 清空集合并判断是否为空
fruits.clear();
System.out.println("集合是否为空:" + fruits.isEmpty());
}
}
输出结果
初始集合元素:
Apple Banana Cherry Date Elderberry
-----
修改后集合元素:
Apple Blueberry Date Elderberry
-----
Date 存在,索引为:2
-----
集合是否为空:true
练习题2:中等难度 - HashSet 去重与排序
题目:现有一组重复的整数:{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}
,使用HashSet
对其去重,然后将去重后的元素存入ArrayList
并按从小到大排序,最后打印结果。
解题思路
- 创建
HashSet
,添加所有整数(自动去重)。 - 将
HashSet
转换为ArrayList
(利用ArrayList
的构造方法new ArrayList<>(collection)
)。 - 使用
Collections.sort()
对ArrayList
排序。 - 打印排序后的结果。
代码实现
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class HashSetExercise {
public static void main(String[] args) {
// 原始数组(含重复元素)
int[] nums = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
// 1. 使用HashSet去重
Set<Integer> numSet = new HashSet<>();
for (int num : nums) {
numSet.add(num);
}
System.out.println("去重后的元素(无序):" + numSet);
// 2. 转换为ArrayList并排序
List<Integer> numList = new ArrayList<>(numSet);
Collections.sort(numList); // 从小到大排序
// 3. 打印排序结果
System.out.println("排序后的元素(有序):" + numList);
}
}
输出结果
去重后的元素(无序):[1, 2, 3, 4, 5, 6, 9]
排序后的元素(有序):[1, 2, 3, 4, 5, 6, 9]
练习题3:进阶难度 - TreeMap 统计字符出现次数
题目:给定字符串"hello world java programming"
,使用TreeMap
统计每个字符(不区分大小写,忽略空格)出现的次数,并按字符顺序输出结果(如a:2, d:1, e:1...
)。
解题思路
- 预处理字符串:转换为小写(
toLowerCase()
),去除空格(replaceAll(" ", "")
)。 - 创建
TreeMap<Character, Integer>
,key
为字符,value
为出现次数。 - 遍历字符串的每个字符:
- 若
key
已存在,次数+1(put(key, get(key)+1)
)。 - 若
key
不存在,初始化次数为1(put(key, 1)
)。
- 若
- 遍历
TreeMap
,按格式输出每个字符的次数(TreeMap
自动按key
排序)。
代码实现
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class TreeMapExercise {
public static void main(String[] args) {
String str = "hello world java programming";
// 预处理:转小写,去空格
String processed = str.toLowerCase().replaceAll(" ", "");
System.out.println("处理后的字符串:" + processed);
// 创建TreeMap统计字符次数
TreeMap<Character, Integer> charCount = new TreeMap<>();
// 遍历每个字符并统计
for (int i = 0; i < processed.length(); i++) {
char c = processed.charAt(i);
// 若字符已存在,次数+1;否则初始化为1
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
// 按字符顺序输出结果
System.out.println("字符出现次数:");
Set<Map.Entry<Character, Integer>> entries = charCount.entrySet();
for (Map.Entry<Character, Integer> entry : entries) {
System.out.print(entry.getKey() + ":" + entry.getValue() + ", ");
}
}
}
输出结果
处理后的字符串:helloworldjavaprogramming
字符出现次数:
a:2, g:2, i:1, j:1, l:3, m:2, n:1, o:3, p:1, r:2, v:1, w:1,
练习题4:综合难度 - 集合嵌套应用
题目:模拟班级学生成绩管理系统:
- 创建
Student
类(包含name
和score
属性,重写toString()
)。 - 使用
HashMap<String, List<Student>>
存储多个班级的学生列表(key
为班级名称,value
为该班级学生的ArrayList
)。 - 向集合中添加3个班级,每个班级至少3名学生。
- 遍历集合,打印每个班级的名称、学生总数及所有学生信息。
- 统计并打印所有班级中分数最高的学生信息(若有多个同分,都打印)。
解题思路
- 定义
Student
类,封装name
和score
,重写toString()
方便打印。 - 创建
HashMap
存储班级与学生的映射,用put()
添加班级和学生列表。 - 遍历
HashMap
的entrySet()
,获取每个班级的学生列表,统计总数并打印学生信息。 - 找出最高分:遍历所有学生,记录最高分,再遍历一次收集所有最高分学生并打印。
代码实现
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
// 学生类
class Student {
private String name;
private double score;
public Student(String name, double score) {
this.name = name;
this.score = score;
}
public double getScore() {
return score;
}
@Override
public String toString() {
return "Student{name='" + name + "', score=" + score + "}";
}
}
public class CollectionNestingExercise {
public static void main(String[] args) {
// 1. 创建班级-学生映射
Map<String, List<Student>> classStudents = new HashMap<>();
// 2. 添加班级和学生
// 班级1
List<Student> class1 = new ArrayList<>();
class1.add(new Student("张三", 90));
class1.add(new Student("李四", 85));
class1.add(new Student("王五", 95));
classStudents.put("高一(1)班", class1);
// 班级2
List<Student> class2 = new ArrayList<>();
class2.add(new Student("赵六", 88));
class2.add(new Student("孙七", 92));
class2.add(new Student("周八", 80));
classStudents.put("高一(2)班", class2);
// 班级3
List<Student> class3 = new ArrayList<>();
class3.add(new Student("吴九", 95));
class3.add(new Student("郑十", 89));
class3.add(new Student("钱十一", 93));
classStudents.put("高一(3)班", class3);
// 3. 遍历并打印每个班级信息
System.out.println("===== 班级学生信息 =====");
Set<Map.Entry<String, List<Student>>> entries = classStudents.entrySet();
for (Map.Entry<String, List<Student>> entry : entries) {
String className = entry.getKey();
List<Student> students = entry.getValue();
System.out.println("班级:" + className + ",学生总数:" + students.size());
for (Student s : students) {
System.out.println(" " + s);
}
}
// 4. 统计最高分学生
double maxScore = -1;
// 第一次遍历:找出最高分
for (List<Student> students : classStudents.values()) {
for (Student s : students) {
if (s.getScore() > maxScore) {
maxScore = s.getScore();
}
}
}
// 第二次遍历:收集所有最高分学生
List<Student> topStudents = new ArrayList<>();
for (List<Student> students : classStudents.values()) {
for (Student s : students) {
if (s.getScore() == maxScore) {
topStudents.add(s);
}
}
}
// 打印最高分学生
System.out.println("\n===== 最高分学生(" + maxScore + "分) =====");
for (Student s : topStudents) {
System.out.println(s);
}
}
}
输出结果
===== 班级学生信息 =====
班级:高一(1)班,学生总数:3
Student{name='张三', score=90.0}
Student{name='李四', score=85.0}
Student{name='王五', score=95.0}
班级:高一(2)班,学生总数:3
Student{name='赵六', score=88.0}
Student{name='孙七', score=92.0}
Student{name='周八', score=80.0}
班级:高一(3)班,学生总数:3
Student{name='吴九', score=95.0}
Student{name='郑十', score=89.0}
Student{name='钱十一', score=93.0}
===== 最高分学生(95.0分) =====
Student{name='王五', score=95.0}
Student{name='吴九', score=95.0}
总结
- 练习题1:掌握
ArrayList
的基本CRUD操作和遍历方式。 - 练习题2:理解
HashSet
的去重特性,以及集合间的转换和排序。 - 练习题3:熟悉
TreeMap
的排序功能,用于统计场景。 - 练习题4:综合应用集合嵌套(
Map
嵌套List
),模拟实际业务数据结构,强化多集合协同操作能力。
通过这些练习,可深入理解不同集合的特性和适用场景,提升集合框架的实际应用能力。