文章目录331. Java Stream API - Java Stream 实战案例找出合作最多的作者对 目标 数据模型设计️ 构建作者对流 展平所有文章的作者对 构建作者对出现频次的直方图 找出合作最多的一对作者 示例数据和完整运行逻辑 小结与思考331. Java Stream API - Java Stream 实战案例找出合作最多的作者对 目标在一堆文章Article中找出一起合作写文章次数最多的两个作者Author。 数据模型设计我们有三个核心模型// 作者支持按名字排序recordAuthor(Stringname)implementsComparableAuthor{publicintcompareTo(Authorother){returnthis.name.compareTo(other.name);}}// 文章recordArticle(Stringtitle,intinceptionYear,ListAuthorauthors){}// 作者对避免重复如 A-B 和 B-A 视为同一对recordPairOfAuthors(Authorfirst,Authorsecond){publicstaticOptionalPairOfAuthorsof(Authorfirst,Authorsecond){// 确保作者对排序一致避免 A-B 和 B-Aif(first.compareTo(second)0){returnOptional.of(newPairOfAuthors(first,second));}else{returnOptional.empty();}}}PairOfAuthors.of()用Optional表示“是否是有效的作者对”这样可以方便后续的流式处理。️ 构建作者对流第一步是从每篇文章中提取所有合法的作者对。BiFunctionArticle,Author,StreamPairOfAuthorsbuildPairOfAuthors(article,firstAuthor)-article.authors().stream().flatMap(secondAuthor-PairOfAuthors.of(firstAuthor,secondAuthor).stream()); 如果PairOfAuthors.of()返回Optional.empty()那么stream()就是空流否则是单元素流。这样可以优雅地处理无效对。 展平所有文章的作者对FunctionArticle,StreamPairOfAuthorstoPairOfAuthorsarticle-article.authors().stream().flatMap(firstAuthor-buildPairOfAuthors.apply(article,firstAuthor)); 我们对每篇文章的作者使用flatMap()构建所有可能的作者对去除无效。 构建作者对出现频次的直方图MapPairOfAuthors,LongnumberOfAuthorsTogetherarticles.stream().flatMap(toPairOfAuthors).collect(Collectors.groupingBy(Function.identity(),Collectors.counting())); 用groupingBycounting()聚合每对作者出现的次数。 找出合作最多的一对作者FunctionMapPairOfAuthors,Long,Map.EntryPairOfAuthors,LongmaxExtractormap-map.entrySet().stream().max(Map.Entry.comparingByValue()).orElseThrow();☂️orElseThrow()会在没有任何作者对时抛异常所以要确保至少有一篇文章包含两个作者。 示例数据和完整运行逻辑varmarianewAuthor(Maria);varjamesnewAuthor(James);varpatricianewAuthor(Patricia);varmichaelnewAuthor(Michael);vararticlesList.of(newArticle(About As You Like It,2015,List.of(maria)),newArticle(About King John,2015,List.of(james)),newArticle(About The Winters 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.EntryPairOfAuthors,LongpairmaxExtractor.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()获取最大值时要注意异常安全性