Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
利用Java Stream API高效分组与转换实体数据_创想鸟

利用Java Stream API高效分组与转换实体数据

利用java stream api高效分组与转换实体数据

本文深入探讨如何利用Java Stream API高效地对实体列表进行分组,并对分组后的元素进行自定义映射。通过结合`Collectors.groupingBy`和`Collectors.mapping`,我们能够将原始实体列表转换为指定字段的映射结构,从而实现更简洁、可读性更强的数据处理逻辑,显著优化了传统循环的冗余和复杂性。

数据分组与自定义映射的需求

在数据处理场景中,我们经常面临这样的需求:从一个对象集合中,根据某个特定的属性进行分组,然后对每个分组内的对象,提取或转换成另一种形式的数据。例如,我们有一个RegistryEntity列表,其中每个实体包含ID、姓名(Name)和城市(City)信息,其结构如下:

Id Name City

1JohnNew York2PaulAtlanta3MarkLos Angeles4SusanLos Angeles5JoshNew York6CharlesAtlanta

我们的目标是根据City字段对这些实体进行分组,但最终结果不是Map<String, List>,而是Map<String, List>,其中键是城市名,值是该城市下所有用户的姓名列表,例如:

{  "New York": ["John", "Josh"],  "Atlanta": ["Paul", "Charles"],  "Los Angeles": ["Mark", "Susan"]}

传统循环实现方式及其局限

在Java 8之前,或者不熟悉Stream API时,我们通常会采用传统的循环遍历方式来实现这一需求。以下是一个典型的实现示例:

立即学习“Java免费学习笔记(深入)”;

import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;// 假设 RegistryEntity 类的定义如下:class RegistryEntity {    private int id;    private String name;    private String city;    public RegistryEntity(int id, String name, String city) {        this.id = id;        this.name = name;        this.city = city;    }    public String getName() { return name; }    public String getCity() { return city; }    // 其他 getter/setter 省略}public class TraditionalGrouping {    public Map<String, List> findAllUsers(List items) {        Map<String, List> itemsGrouped = new HashMap();        for (RegistryEntity s : items) {            String city = s.getCity();            String name = s.getName();            // 检查该城市是否已存在于Map中            if (itemsGrouped.containsKey(city)) {                itemsGrouped.get(city).add(name);            } else {                List tempResults = new ArrayList();                tempResults.add(name); // 注意这里是添加 name,而不是 city                itemsGrouped.put(city, tempResults);            }        }        return itemsGrouped;    }    public static void main(String[] args) {        List entities = new ArrayList();        entities.add(new RegistryEntity(1, "John", "New York"));        entities.add(new RegistryEntity(2, "Paul", "Atlanta"));        entities.add(new RegistryEntity(3, "Mark", "Los Angeles"));        entities.add(new RegistryEntity(4, "Susan", "Los Angeles"));        entities.add(new RegistryEntity(5, "Josh", "New York"));        entities.add(new RegistryEntity(6, "Charles", "Atlanta"));        TraditionalGrouping grouper = new TraditionalGrouping();        Map<String, List> result = grouper.findAllUsers(entities);        System.out.println(result);    }}

上述代码虽然能够实现功能,但其缺点在于:

冗余和复杂性: 需要手动管理HashMap的键是否存在,并进行条件判断和列表创建。可读性欠佳: 业务逻辑(分组和映射)与控制流(循环和条件判断)混杂在一起,降低了代码的声明性。非函数式: 这种命令式编程风格不利于代码的并行化处理。

使用Java Stream API优化实现

Java 8引入的Stream API提供了一种更简洁、更具声明性的方式来处理集合数据。通过结合Collectors.groupingBy和Collectors.mapping,我们可以优雅地实现上述分组和自定义映射的需求。

Collectors.groupingBy是一个非常强大的收集器,它根据一个分类函数对流中的元素进行分组,并返回一个Map。它的重载形式允许我们指定一个“下游收集器”(downstream collector),用于处理每个分组中的元素。

叮当好记-AI音视频转图文 叮当好记-AI音视频转图文

AI音视频转录与总结,内容学习效率 x10!

叮当好记-AI音视频转图文 193 查看详情 叮当好记-AI音视频转图文

Collectors.mapping则是一个下游收集器,它将输入元素应用一个映射函数,然后将映射后的结果收集到另一个收集器中。这正是我们需要的:在按城市分组后,将每个RegistryEntity映射为其name,然后将这些name收集到一个列表中。

以下是使用Stream API实现的代码:

import java.util.List;import java.util.Map;import java.util.stream.Collectors;import java.util.ArrayList; // 仅用于示例数据// RegistryEntity 类定义同上// class RegistryEntity { ... }public class StreamGrouping {    public Map<String, List> findAllUsersOptimized(List items) {        Map<String, List> itemsGrouped =            items.stream()                 .collect(Collectors.groupingBy(                     RegistryEntity::getCity, // 分组键:按城市分组                     Collectors.mapping(RegistryEntity::getName, Collectors.toList()) // 下游收集器:将每个实体映射为姓名,并收集到列表中                 ));        return itemsGrouped;    }    public static void main(String[] args) {        List entities = new ArrayList();        entities.add(new RegistryEntity(1, "John", "New York"));        entities.add(new RegistryEntity(2, "Paul", "Atlanta"));        entities.add(new RegistryEntity(3, "Mark", "Los Angeles"));        entities.add(new RegistryEntity(4, "Susan", "Los Angeles"));        entities.add(new RegistryEntity(5, "Josh", "New York"));        entities.add(new RegistryEntity(6, "Charles", "Atlanta"));        StreamGrouping grouper = new StreamGrouping();        Map<String, List> result = grouper.findAllUsersOptimized(entities);        System.out.println(result);        // 预期输出: {New York=[John, Josh], Atlanta=[Paul, Charles], Los Angeles=[Mark, Susan]}    }}

代码解析

让我们详细分解Stream管道中的各个部分:

items.stream(): 将RegistryEntity列表转换为一个Stream流。这是所有Stream操作的起点。.collect(…): 这是一个终端操作,用于将Stream中的元素收集到一个结果容器中。我们在这里使用Collectors类提供的静态工厂方法。Collectors.groupingBy(…): 这是核心的分组操作。它接受两个参数:RegistryEntity::getCity: 这是一个分类函数(Function),它定义了如何从RegistryEntity中提取用于分组的键。在这里,我们使用方法引用,表示根据RegistryEntity对象的city属性进行分组。Collectors.mapping(RegistryEntity::getName, Collectors.toList()): 这是下游收集器。对于每个城市分组,它会执行以下操作:RegistryEntity::getName: 这是一个映射函数(Function),它将每个RegistryEntity对象转换为其name属性(一个String)。Collectors.toList(): 这是一个最终收集器,它将所有映射后的name字符串收集到一个新的List中。

通过这种组合,groupingBy首先按城市将RegistryEntity对象分桶,然后对于每个桶,mapping收集器会取出桶中每个实体的姓名,并将这些姓名收集成一个列表。最终,groupingBy将这些城市和对应的姓名列表组合成一个Map<String, List>。

优势与注意事项

优势:

简洁性与可读性: Stream API的代码更加紧凑和富有表达力,业务逻辑一目了然。声明式编程: 你只需声明“做什么”(按城市分组,然后收集姓名列表),而无需关心“如何做”(循环、条件判断、手动创建列表)。易于并行化: Stream API支持并行流(通过parallelStream()),在处理大量数据时,可以轻松利用多核CPU的优势,提升性能(尽管对于小规模数据,并行流的开销可能大于收益)。函数式风格: 鼓励使用不可变数据和纯函数,有助于编写更健壮、更易于测试的代码。

注意事项:

空值处理: 如果RegistryEntity::getCity或RegistryEntity::getName可能返回null,需要根据具体业务需求进行额外的处理,例如使用filter过滤掉null值,或者在映射函数中处理null。性能考量: 对于非常小的数据集,传统循环的性能开销可能略低于Stream API,因为Stream引入了一些抽象层。但在大多数实际应用中,Stream API的性能表现良好,且其带来的代码可读性和维护性收益通常远超微小的性能差异。选择合适的收集器: Collectors类提供了丰富的收集器,例如counting()、summingInt()、averagingInt()等,可以根据不同的聚合需求选择合适的下游收集器。

总结

Java Stream API为集合数据的处理带来了革命性的变革。通过巧妙地结合Collectors.groupingBy和Collectors.mapping,我们能够以一种高度声明式、简洁且高效的方式实现复杂的数据分组和转换需求。这种方法不仅提升了代码的可读性和可维护性,也为处理大规模数据集提供了并行化的可能性,是现代Java开发中不可或缺的工具。掌握Stream API及其丰富的收集器,将使你的数据处理代码更加优雅和强大。

以上就是利用Java Stream API高效分组与转换实体数据的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/578750.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
webp怎么查看参数_webp如何查看参数
上一篇 2025年11月10日 09:41:02
惠普台式机显卡选择及安装注意事项详细解析
下一篇 2025年11月10日 09:41:15

相关推荐

发表回复

登录后才能评论
关注微信