当前位置: 首页 > news >正文

331. Java Stream API - Java Stream 实战案例:找出合作最多的作者对

文章目录

  • 331. Java Stream API - Java Stream 实战案例:找出合作最多的作者对
    • 🎯 目标
    • 🧩 数据模型设计
    • 🏗️ 构建作者对流
    • 🔁 展平所有文章的作者对
    • 📊 构建作者对出现频次的直方图
    • 🥇 找出合作最多的一对作者
    • 🧪 示例数据和完整运行逻辑
    • 💡 小结与思考

331. Java Stream API - Java Stream 实战案例:找出合作最多的作者对

🎯 目标

在一堆文章(Article)中,找出一起合作写文章次数最多的两个作者(Author)


🧩 数据模型设计

我们有三个核心模型:

// 作者,支持按名字排序recordAuthor(Stringname)implementsComparable<Author>{publicintcompareTo(Authorother){returnthis.name.compareTo(other.name);}}// 文章recordArticle(Stringtitle,intinceptionYear,List<Author>authors){}// 作者对(避免重复,如 A-B 和 B-A 视为同一对)recordPairOfAuthors(Authorfirst,Authorsecond){publicstaticOptional<PairOfAuthors>of(Authorfirst,Authorsecond){// 确保作者对排序一致(避免 A-B 和 B-A)if(first.compareTo(second)>0){returnOptional.of(newPairOfAuthors(first,second));}else{returnOptional.empty();}}}

📌PairOfAuthors.of()Optional表示“是否是有效的作者对”,这样可以方便后续的流式处理。


🏗️ 构建作者对流

第一步是:从每篇文章中提取所有合法的作者对。

BiFunction<Article,Author,Stream<PairOfAuthors>>buildPairOfAuthors=(article,firstAuthor)->article.authors().stream().flatMap(secondAuthor->PairOfAuthors.of(firstAuthor,secondAuthor).stream());

🔍 如果PairOfAuthors.of()返回Optional.empty(),那么stream()就是空流,否则是单元素流。这样可以优雅地处理无效对。


🔁 展平所有文章的作者对

Function<Article,Stream<PairOfAuthors>>toPairOfAuthors=article->article.authors().stream().flatMap(firstAuthor->buildPairOfAuthors.apply(article,firstAuthor));

💡 我们对每篇文章的作者使用flatMap(),构建所有可能的作者对(去除无效)。


📊 构建作者对出现频次的直方图

Map<PairOfAuthors,Long>numberOfAuthorsTogether=articles.stream().flatMap(toPairOfAuthors).collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));

📦 用groupingBy+counting()聚合每对作者出现的次数。


🥇 找出合作最多的一对作者

Function<Map<PairOfAuthors,Long>,Map.Entry<PairOfAuthors,Long>>maxExtractor=map->map.entrySet().stream().max(Map.Entry.comparingByValue()).orElseThrow();

☂️orElseThrow()会在没有任何作者对时抛异常,所以要确保至少有一篇文章包含两个作者。


🧪 示例数据和完整运行逻辑

varmaria=newAuthor("Maria");varjames=newAuthor("James");varpatricia=newAuthor("Patricia");varmichael=newAuthor("Michael");vararticles=List.of(newArticle("About As You Like It",2015,List.of(maria)),newArticle("About King John",2015,List.of(james)),newArticle("About The Winter's Tale",2016,List.of(patricia)),newArticle("About Richard II",2017,List.of(michael)),newArticle("About Richard III",2019,List.of(maria,patricia)),newArticle("About Henry VIII",20219,List.of(patricia,michael)),newArticle("About Romeo and Juliet",2020,List.of(maria,patricia,james)),newArticle("About Macbeth",2021,List.of(maria,james,michael)),newArticle("About Hamlet",2021,List.of(patricia,james,michael)),newArticle("About King Lear",2022,List.of(maria,james,patricia,michael)));Map.Entry<PairOfAuthors,Long>pair=maxExtractor.apply(numberOfAuthorsTogether);System.out.println("The authors that published the most together are "+pair.getKey().first().name()+" and "+pair.getKey().second().name()+", they wrote "+pair.getValue()+" articles together.");

🧾输出结果:

Theauthors that published the most together arePatriciaandMichael,they wrote3articles together.

💡 小结与思考

✅ 使用Optional.stream()可以优雅处理“可能不存在”的值
✅ 用flatMap()组合嵌套结构(多个 List 变为流)
groupingBy + counting构建频次统计
max()+orElseThrow()获取最大值时要注意异常安全性

http://www.jsqmd.com/news/401993/

相关文章:

  • ChatTTS音色技术解析:从原理到工程实践
  • CosyVoice 2 加速实战:从零搭建高性能语音处理系统
  • 【当代AI入门宝典】:从工具到实战,程序员必懂的效率提效全攻略
  • Node.js 接入 Seedance 2.0 的终极决策模型(企业级计费陷阱识别矩阵 v2.3)
  • 【仅限首批200家企业开放】Seedance 2.0算力成本健康度深度审计(含GPU/TPU/FPGA异构资源归因分析报告)
  • 基于Dify智能体构建高可用客服助手的架构设计与避坑指南
  • 【紧急预警】Seedance 2.0 v2.3.0已触发默认高开销配置!立即执行这7步降本校准,否则下月账单将激增210%
  • 【问题反馈】JNI 开发:为什么 C++ 在 Debug 正常,Release 却返回 NaN?
  • CMW500如何通过VoLTE语音通话实现高效测试:原理与实战指南
  • Seedance 2.0 SDK Node.js 快速集成实战(含CI/CD自动化部署模板)
  • Seedance 2.0 SDK 在 Node.js 中部署失败的93%原因曝光:3个致命配置陷阱你中招了吗?
  • AI视频生成模型从无到有:构建、实现与调试完全指南
  • 【Seedance 2.0算力成本优化白皮书】:20年架构师亲授3类GPU调度降本法,实测单任务成本直降67.3%
  • 基于深度学习毕业设计开源:从模型训练到部署的实战全流程
  • 2026更新版!AI论文网站 千笔 VS 灵感风暴AI,专科生写作神器!
  • 【Seedance 2.0算力成本优化白皮书】:20年架构师亲授3大降本杠杆+实测压降47%的私有部署方案
  • 当人人都会用AI,你靠什么脱颖而出?
  • 计算机毕设选题1000个:如何通过智能筛选与工具链提升选题效率
  • C++流程控制语句:构建结构化程序的核心
  • C、C++区别还是蛮大的
  • 【Seedance 2.0 SDK Node.js 部署权威指南】:2026年唯一经官方认证的零故障落地手册(含3大避坑清单+性能压测基准数据)
  • Seedance 2.0算力定价模型解密:为什么同样vCPU,A区比B区贵31%?——跨可用区成本避坑指南
  • ChatTTS Mac版实战:AI辅助开发中的高效下载与集成指南
  • 前端开发者必备的UI灵感宝库:最全参考网站指南
  • 冷启动延迟从2.8s降至186ms,Seedance 2.0 + Node.js 20.x 的4步热加载优化,附压测对比数据
  • Seedance 2.0算力成本突增预警API:实时监测+自动熔断,上线72小时内拦截无效调用230万次
  • 【Linux】应用层协议http
  • Bash 循环与函数、Linux 进程管理
  • 写作压力小了!10个降AI率工具测评:专科生必看的降AI率神器推荐
  • Seedance 2.0 Node.js 集成全链路优化(含性能压测数据+内存泄漏修复实录)