我将基于Java 8+的新特性和现代开发实践,结合实际场景,为你提供Java集合容器的实操内容。以下代码展示了如何使用Java集合框架的高级特性解决实际问题。
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CollectionPractice {
// 1. 使用Stream API处理集合
public static void streamApiExample() {
List<String> words = Arrays.asList("apple", "banana", "cherry", "date", "elderberry");
// 过滤长度大于5的单词,转换为大写,收集到新列表
List<String> filteredWords = words.stream()
.filter(word -> word.length() > 5)
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println("过滤后的单词: " + filteredWords);
// 计算所有单词的字符总数
int totalLength = words.stream()
.mapToInt(String::length)
.sum();
System.out.println("字符总数: " + totalLength);
// 按长度分组单词
Map<Integer, List<String>> wordsByLength = words.stream()
.collect(Collectors.groupingBy(String::length));
System.out.println("按长度分组: " + wordsByLength);
}
// 2. 使用ConcurrentHashMap处理并发场景
public static void concurrentHashMapExample() {
ConcurrentHashMap<String, Integer> wordCounts = new ConcurrentHashMap<>();
List<String> documents = Arrays.asList(
"Java is a popular programming language",
"Python is another popular programming language",
"Java and Python are widely used in data science"
);
// 并行处理文档,统计单词频率
documents.parallelStream()
.flatMap(doc -> Arrays.stream(doc.split(" ")))
.forEach(word -> wordCounts.compute(word, (k, v) -> v == null ? 1 : v + 1));
System.out.println("单词频率统计: " + wordCounts);
}
// 3. 使用LinkedHashMap实现LRU缓存
public static void lruCacheExample() {
// 容量为3的LRU缓存
LinkedHashMap<String, String> lruCache = new LinkedHashMap<String, String>(3, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<String, String> eldest) {
return size() > 3;
}
};
lruCache.put("key1", "value1");
lruCache.put("key2", "value2");
lruCache.put("key3", "value3");
System.out.println("缓存内容: " + lruCache);
// 访问key2,使其变为最近使用
lruCache.get("key2");
System.out.println("访问key2后: " + lruCache);
// 添加新元素,触发LRU淘汰
lruCache.put("key4", "value4");
System.out.println("添加key4后: " + lruCache); // key1应被淘汰
}
// 4. 使用TreeSet对自定义对象排序
public static void treeSetSortingExample() {
// 按价格排序的商品集合
TreeSet<Product> products = new TreeSet<>(Comparator.comparingDouble(Product::getPrice));
products.add(new Product("Laptop", 1200.0));
products.add(new Product("Mouse", 25.0));
products.add(new Product("Monitor", 300.0));
System.out.println("按价格排序的商品:");
products.forEach(System.out::println);
}
// 5. 使用Map的computeIfAbsent方法优化缓存加载
public static void computeIfAbsentExample() {
Map<String, List<String>> userRoles = new HashMap<>();
// 传统方式
String username = "admin";
List<String> roles = userRoles.get(username);
if (roles == null) {
roles = new ArrayList<>();
userRoles.put(username, roles);
}
roles.add("ADMIN");
roles.add("USER");
// 使用computeIfAbsent简化
userRoles.computeIfAbsent("user1", k -> new ArrayList<>()).add("USER");
System.out.println("用户角色: " + userRoles);
}
// 6. 使用EnumMap存储枚举值映射
public static void enumMapExample() {
enum Weekday {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
EnumMap<Weekday, String> schedule = new EnumMap<>(Weekday.class);
schedule.put(Weekday.MONDAY, "Meeting");
schedule.put(Weekday.TUESDAY, "Training");
schedule.put(Weekday.WEDNESDAY, "Project work");
System.out.println("周三安排: " + schedule.get(Weekday.WEDNESDAY));
}
// 7. 使用集合进行数据统计
public static void statisticsExample() {
List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5);
// 使用IntSummaryStatistics进行统计
IntSummaryStatistics stats = numbers.stream()
.mapToInt(Integer::intValue)
.summaryStatistics();
System.out.println("统计信息:");
System.out.println("总数: " + stats.getCount());
System.out.println("总和: " + stats.getSum());
System.out.println("平均值: " + stats.getAverage());
System.out.println("最大值: " + stats.getMax());
System.out.println("最小值: " + stats.getMin());
}
// 8. 使用集合去重和转换
public static void distinctAndMapExample() {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Alice", "David");
// 去重并转换为大写
List<String> uniqueNames = names.stream()
.distinct()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println("去重并大写后的名字: " + uniqueNames);
}
// 9. 使用队列实现任务调度
public static void queueExample() {
// 优先队列(最小堆)
PriorityQueue<Task> taskQueue = new PriorityQueue<>(Comparator.comparingInt(Task::getPriority));
taskQueue.add(new Task("Task 1", 3));
taskQueue.add(new Task("Task 2", 1));
taskQueue.add(new Task("Task 3", 2));
System.out.println("任务执行顺序:");
while (!taskQueue.isEmpty()) {
System.out.println(taskQueue.poll());
}
}
// 10. 使用集合交集、并集和差集操作
public static void setOperationsExample() {
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Set<Integer> set2 = new HashSet<>(Arrays.asList(4, 5, 6, 7, 8));
// 交集
Set<Integer> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
System.out.println("交集: " + intersection);
// 并集
Set<Integer> union = new HashSet<>(set1);
union.addAll(set2);
System.out.println("并集: " + union);
// 差集
Set<Integer> difference = new HashSet<>(set1);
difference.removeAll(set2);
System.out.println("差集 (set1 - set2): " + difference);
}
public static void main(String[] args) {
System.out.println("=== Stream API示例 ===");
streamApiExample();
System.out.println("\n=== ConcurrentHashMap示例 ===");
concurrentHashMapExample();
System.out.println("\n=== LRU缓存示例 ===");
lruCacheExample();
System.out.println("\n=== TreeSet排序示例 ===");
treeSetSortingExample();
System.out.println("\n=== computeIfAbsent示例 ===");
computeIfAbsentExample();
System.out.println("\n=== EnumMap示例 ===");
enumMapExample();
System.out.println("\n=== 统计示例 ===");
statisticsExample();
System.out.println("\n=== 去重和转换示例 ===");
distinctAndMapExample();
System.out.println("\n=== 队列示例 ===");
queueExample();
System.out.println("\n=== 集合操作示例 ===");
setOperationsExample();
}
// 商品类,用于TreeSet示例
static class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public double getPrice() {
return price;
}
@Override
public String toString() {
return name + ": $" + price;
}
}
// 任务类,用于队列示例
static class Task {
private String name;
private int priority;
public Task(String name, int priority) {
this.name = name;
this.priority = priority;
}
public int getPriority() {
return priority;
}
@Override
public String toString() {
return name + " (优先级: " + priority + ")";
}
}
}
上述代码展示了Java集合容器的现代使用方式,包括:
- Stream API的使用:通过流式操作过滤、映射和收集集合元素,实现复杂的数据处理。
- 并发集合:使用
ConcurrentHashMap
在多线程环境中高效地处理共享数据。 - LRU缓存实现:通过
LinkedHashMap
的访问顺序特性实现LRU缓存策略。 - 自定义排序:使用
TreeSet
和Comparator
对自定义对象进行排序。 - 集合操作优化:利用
computeIfAbsent
等方法简化集合操作,避免空值检查。 - 专用集合:展示
EnumMap
等针对特定场景优化的集合类。 - 统计功能:使用
IntSummaryStatistics
等工具类进行数据统计。 - 集合运算:实现集合的交集、并集和差集操作。
这些示例覆盖了日常开发中常见的场景,展示了如何利用Java集合框架的高级特性编写简洁、高效的代码。
Java 集合框架,ArrayList,HashMap,LinkedList,HashSet,ConcurrentHashMap, 集合性能优化,集合线程安全,集合遍历技巧,集合排序,集合去重,集合转换,Java 集合面试题,Java8 集合新特性,集合实战案例
代码获取方式
https://pan.quark.cn/s/14fcf913bae6