Java练习——day2(集合嵌套)
文章目录
- 练习1
- 练习2
- 练习3
练习1
给定一个字符串列表List words,统计每个单词出现的次数,并用Map<String, Integer>存储结果。
示例代码:
import java.util.*;public class WordCount {public static void main(String[] args) {// 示例单词列表List<String> words = Arrays.asList("apple", "banana", "apple", "orange", "banana", "apple");// 创建 Map 用于存储每个单词及其出现次数Map<String, Integer> wordCountMap = new HashMap<>();// 遍历单词列表,统计每个单词出现的次数for (String word : words) {// 如果存在则加1,否则存入1wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);}// 输出结果:遍历 Map 并打印每个单词和对应的计数for (Map.Entry<String, Integer> entry : wordCountMap.entrySet()) {System.out.println(entry.getKey() + " : " + entry.getValue());}}
}
- 代码解析
- 数据准备:
使用 Arrays.asList 创建了一个示例单词列表 words。 - 统计逻辑:
利用 HashMap 来存储单词及其出现次数。通过 getOrDefault(word, 0) 方法获取当前单词计数(如果不存在则默认为 0),然后加 1,再存入 Map。 - 结果输出:
练习2
创建一个Student类(含name和score字段),将多个Student对象存入List,按分数从高到低排序。
代码示例:
import java.util.*;// 定义 Student 类,包含 name 和 score 字段
class Student {private String name;private int score;public Student(String name, int score) {this.name = name;this.score = score;}// 提供 getter 方法public String getName() {return name;}public int getScore() {return score;}// 重写 toString 方法以便打印 Student 对象信息@Overridepublic String toString() {return "Student{name='" + name + "', score=" + score + "}";}
}public class StudentSort {public static void main(String[] args) {// 创建一个 List 存储 Student 对象List<Student> students = new ArrayList<>();students.add(new Student("Alice", 85));students.add(new Student("Bob", 92));students.add(new Student("Charlie", 78));// 使用 Collections.sort 方法排序,按分数从高到低排列Collections.sort(students, new Comparator<Student>() {@Overridepublic int compare(Student s1, Student s2) {// 返回负值表示 s1 排在 s2 前面,这里用 s2-score - s1-score 实现降序排序return s2.getScore() - s1.getScore();}});// 或者使用 lambda 表达式简化写法:// students.sort((s1, s2) -> s2.getScore() - s1.getScore());// 输出排序后的 Student 列表for (Student student : students) {System.out.println(student);}}
}
-
代码解析
-
Student 类定义:
Student 类包含私有的 name 和 score 字段,并提供构造方法和 getter 方法;重写了 toString 方法,便于输出对象信息。 -
学生数据列表:
在 main 方法中,使用 ArrayList 存储多个 Student 对象。 -
排序操作:
调用 Collections.sort 方法,并传入一个自定义的 Comparator,比较两个 Student 对象的分数,从而实现按分数从高到低(降序)排序。代码中也给出了使用 lambda 表达式的简化写法示例。 -
结果输出:
练习3
实现一个LRU(最近最少使用)缓存,使用LinkedHashMap或其他集合,确保插入和查询的时间复杂度为O(1)。
示例代码:
import java.util.*;public class LRUCache<K, V> extends LinkedHashMap<K, V> {private final int capacity;/*** 构造方法* @param capacity 缓存的最大容量*/public LRUCache(int capacity) {// 调用 LinkedHashMap 的构造函数,设置 accessOrder 为 true,// 这样会按照访问顺序排列元素,最近访问的元素会移动到链表尾部super(capacity, 0.75f, true);this.capacity = capacity;}/*** 重写 removeEldestEntry 方法,当缓存大小超过 capacity 时返回 true,从而移除最不常使用的元素。*/@Overrideprotected boolean removeEldestEntry(Map.Entry<K, V> eldest) {return size() > capacity;}public static void main(String[] args) {// 创建容量为3的 LRU 缓存实例LRUCache<Integer, String> cache = new LRUCache<>(3);// 插入元素cache.put(1, "one");cache.put(2, "two");cache.put(3, "three");System.out.println("初始缓存:" + cache);// 访问 key 为 1 的元素,使其变为最近访问项cache.get(1);// 插入新元素,缓存超过容量会自动淘汰最久未使用的元素cache.put(4, "four");System.out.println("访问 key 1 后插入新元素 4:" + cache);// 根据使用顺序,此时 key 2 将被淘汰,因为它是最久未使用的元素}
}
-
代码解析
-
继承 LinkedHashMap:
通过继承 LinkedHashMap,利用其按访问顺序排序的特性(构造函数的第三个参数 accessOrder 设置为 true)实现 LRU 缓存。 -
容量控制:
重写 removeEldestEntry 方法。当 size() > capacity 时,返回 true,使得 LinkedHashMap 自动移除最久未使用的键值对。 -
性能特点:
插入(put)和查询(get)操作均能达到 O(1) 的时间复杂度。 -
测试示例:
在 main 方法中,先插入3个元素构成初始缓存;通过访问操作将某个键重新置为最近使用;再插入新元素,从而触发淘汰策略,自动移除最久未访问的键。 -
结果输出: