Java 集合容器实操技巧与案例详解

简介: 本教程基于Java 8+新特性和现代开发实践,深入讲解Java集合容器的实操技巧。通过具体场景演示Stream API数据处理、ConcurrentHashMap并发控制、LinkedHashMap实现LRU缓存、TreeSet自定义排序等高级特性。同时涵盖computeIfAbsent优化操作、EnumMap专用集合使用、集合统计与运算(交集、并集、差集)等内容。代码示例丰富,助力掌握高效编程方法。[点击获取完整代码](https://pan.quark.cn/s/14fcf913bae6)。

我将基于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集合容器的现代使用方式,包括:

  1. Stream API的使用:通过流式操作过滤、映射和收集集合元素,实现复杂的数据处理。
  2. 并发集合:使用ConcurrentHashMap在多线程环境中高效地处理共享数据。
  3. LRU缓存实现:通过LinkedHashMap的访问顺序特性实现LRU缓存策略。
  4. 自定义排序:使用TreeSetComparator对自定义对象进行排序。
  5. 集合操作优化:利用computeIfAbsent等方法简化集合操作,避免空值检查。
  6. 专用集合:展示EnumMap等针对特定场景优化的集合类。
  7. 统计功能:使用IntSummaryStatistics等工具类进行数据统计。
  8. 集合运算:实现集合的交集、并集和差集操作。

这些示例覆盖了日常开发中常见的场景,展示了如何利用Java集合框架的高级特性编写简洁、高效的代码。


Java 集合框架,ArrayList,HashMap,LinkedList,HashSet,ConcurrentHashMap, 集合性能优化,集合线程安全,集合遍历技巧,集合排序,集合去重,集合转换,Java 集合面试题,Java8 集合新特性,集合实战案例



代码获取方式
https://pan.quark.cn/s/14fcf913bae6


相关文章
|
4月前
|
Java 虚拟化 容器
(Java)Java里JFrame窗体的基本操作(容器布局篇-1)
容器 容器,我的理解是可以包容其他东西的玩意。它可以是一个盒子,可以是一个虚拟化的物品,可只要能包裹住其他存在质体的东西,那么都可以称作是容器。例如:JPanel组件和JScollPane组件两者都是容器也是组件。 既然有容器,那么容器中的布局就必不可少了。不然不规矩的摆放物品,人类看不习惯,我也看不习惯 ???? 本篇内容,将说明java JFrame窗体里容器中几类布局。 说明:所有在JFrame窗体里的容器布局都会使用setLayout()方法,采用的布局参数都将放进这个方法里 绝对布局 调用窗体容器
160 2
|
5月前
|
安全 Java API
Java Web 在线商城项目最新技术实操指南帮助开发者高效完成商城项目开发
本项目基于Spring Boot 3.2与Vue 3构建现代化在线商城,涵盖技术选型、核心功能实现、安全控制与容器化部署,助开发者掌握最新Java Web全栈开发实践。
562 1
|
5月前
|
Java 大数据 API
Java Stream API:现代集合处理与函数式编程
Java Stream API:现代集合处理与函数式编程
325 100
|
5月前
|
Java API 数据处理
Java Stream API:现代集合处理新方式
Java Stream API:现代集合处理新方式
344 101
|
5月前
|
算法 Java
50道java集合面试题
50道 java 集合面试题
|
4月前
|
存储 算法 安全
Java集合框架:理解类型多样性与限制
总之,在 Java 题材中正确地应对多样化与约束条件要求开发人员深入理解面向对象原则、范式编程思想以及JVM工作机理等核心知识点。通过精心设计与周密规划能够有效地利用 Java 高级特征打造出既健壮又灵活易维护系统软件产品。
145 7
|
5月前
|
存储 Java Go
对比Java学习Go——函数、集合和OOP
Go语言的函数支持声明与调用,具备多返回值、命名返回值等特性,结合`func`关键字与类型后置语法,使函数定义简洁直观。函数可作为一等公民传递、赋值或作为参数,支持匿名函数与闭包。Go通过组合与接口实现面向对象编程,结构体定义数据,方法定义行为,接口实现多态,体现了Go语言的简洁与高效设计。
|
6月前
|
Java 测试技术 API
2025 年 Java 开发者必知的最新技术实操指南全览
本指南涵盖Java 21+核心实操,详解虚拟线程、Spring Boot 3.3+GraalVM、Jakarta EE 10+MicroProfile 6微服务开发,并提供现代Java开发最佳实践,助力开发者高效构建高性能应用。
948 4
|
6月前
|
存储 缓存 安全
Java集合框架(三):Map体系与ConcurrentHashMap
本文深入解析Java中Map接口体系及其实现类,包括HashMap、ConcurrentHashMap等的工作原理与线程安全机制。内容涵盖哈希冲突解决、扩容策略、并发优化,以及不同Map实现的适用场景,助你掌握高并发编程核心技巧。
|
5月前
|
Java API 数据库
2025 年最新 Java 实操学习路线,从入门到高级应用详细指南
2025年Java最新实操学习路线,涵盖从环境搭建到微服务、容器化部署的全流程实战内容,助你掌握Java 21核心特性、Spring Boot 3.2开发、云原生与微服务架构,提升企业级项目开发能力,适合从入门到高级应用的学习需求。
1712 0