Java8 Stream 强大功能之统计、汇总、多字段分组和多个列汇总统计【含面试题】

面试题分享点我直达

2023最新面试合集链接

2023大厂面试题PDF

面试题PDF版本

java、python面试题

项目实战:AI文本 OCR识别最佳实践

AI Gamma一键生成PPT工具直达链接

玩转cloud Studio 在线编码神器

玩转 GPU AI绘画、AI讲话、翻译,GPU点亮AI想象空间

史上最全文档AI绘画stablediffusion资料分享

AI绘画关于SD,MJ,GPT,SDXL百科全书

AI绘画 stable diffusion Midjourney 官方GPT文档 AIGC百科全书资料收集

AIGC资料包

在现代Java开发中,Stream API 已经

成为一个强大的工具,它提供了一种简洁而灵活的方式来处理集合数据。其中,Stream API 统计、汇总、多字段分组和多个列汇总统计是使用频率较高的功能。本文将深入介绍这些功能,并提供一些代码示例。

一、统计功能:

  1. count():返回流中元素的总数。
  2. min() 和 max():返回流中的最小值和最大值。
  3. average():返回流中元素的平均值。
  4. sum():对流中的元素求和。

示例代码:

java 复制代码
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

long count = numbers.stream().count();
Optional<Integer> max = numbers.stream().max(Integer::compareTo);
Optional<Integer> min = numbers.stream().min(Integer::compareTo);
double average = numbers.stream().mapToInt(Integer::intValue).average().orElse(0);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();

二、汇总功能:

  1. reduce():将流中的元素进行累积计算,返回一个 Optional 对象。
  2. collect():将流中的元素收集到一个容器对象中,如 List、Set 或 Map。

示例代码:

java 复制代码
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

Optional<Integer> sum = numbers.stream().reduce(Integer::sum);
List<Integer> squaredNumbers = numbers.stream().map(n -> n * n).collect(Collectors.toList());
Set<Integer> evenNumbers = numbers.stream().filter(n -> n % 2 == 0).collect(Collectors.toSet());
Map<String, List<Integer>> groupByOddEven = numbers.stream().collect(Collectors.groupingBy(n -> n % 2 == 0 ? "Even" : "Odd"));

三、多字段分组:

使用 Collectors.groupingBy 方法可以实现对流中元素的多字段分组。

示例代码:

java 复制代码
class Person {
    private String name;
    private int age;
    private String gender;

    // 省略构造函数和 Getter/Setter 方法

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                '}';
    }
}

List<Person> people = Arrays.asList(
        new Person("Alice", 20, "Female"),
        new Person("Bob", 30, "Male"),
        new Person("Charlie", 25, "Male"),
        new Person("David", 22, "Male"),
        new Person("Eva", 28, "Female"),
        new Person("Frank", 35, "Male")
);

Map<String, List<Person>> byGender = people.stream().collect(Collectors.groupingBy(Person::getGender));
Map<Integer, List<Person>> byAge = people.stream().collect(Collectors.groupingBy(Person::getAge));

四、多个列汇总统计:

使用 Collectors.groupingBy 方法结合 Collectors.summarizingInt 方法可以实现对流中元素的多个列进行汇总统计。

示例代码:

java 复制代码
class Product {
    private String category;
    private String name;
    private int price;
    private int quantity;

    // 省略构造函数和 Getter/Setter 方法

    @Override
    public String toString() {
        return "Product{" +
                "category='" + category + '\'' +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", quantity=" + quantity +
                '}';
    }
}

List<Product> products = Arrays.asList(
        new Product("Electronics", "Laptop", 2500, 5),
        new Product("Electronics", "Phone", 800, 3),
        new Product("Clothing", "Shirt", 40, 10),
        new Product("Clothing", "Pants", 60, 8),
        new Product("Books", "Java in Action", 50, 15),
        new Product("Books", "Clean Code", 80, 12)
);

Map<String, IntSummaryStatistics> statsByCategory = products.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.summarizingInt(Product::getQuantity)
相关推荐
2301_767902641 小时前
MySQL 入门
数据库·mysql
7ioik2 小时前
说一说MySQL数据库基本架构?
数据库·mysql·架构
@淡 定2 小时前
Redis持久化机制
数据库·redis·缓存
云老大TG:@yunlaoda3602 小时前
华为云国际站代理商DAS的跨境合规适配是如何保障数据合规的?
网络·数据库·华为云
TG:@yunlaoda360 云老大2 小时前
华为云国际站代理商HiLens的技术优势对跨境客户有哪些具体帮助?
服务器·数据库·华为云
+VX:Fegn08952 小时前
计算机毕业设计|基于springboot + vue健身房管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
Leon-Ning Liu2 小时前
当SGA大于hugepage的时候,Oracle数据库是怎么使用hugepage的
数据库·oracle
马克学长2 小时前
SSM校园二手交易系统aqj3i(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面
数据库·ssm 框架·javaweb 开发
利剑 -~2 小时前
letcode数据库题联系
数据库
小程故事多_803 小时前
Agent Skills深度解析,让智能体从“会连接”到“会做事”的核心引擎
数据库·人工智能·aigc