辛集seo网站优化公司南京网站制作公司有哪些
2026/6/10 20:10:45 网站建设 项目流程
辛集seo网站优化公司,南京网站制作公司有哪些,加速器推荐,郑州网站建设方案php文章目录275. Java Stream API - flatMap 操作#xff1a;展开一对多的关系#xff0c;拉平你的流#xff01;#x1f9e0; 背景#xff1a;我们为什么需要 flatMap#xff1f;#x1f501; 用 flatMap 优雅替代嵌套循环✅ 定义模型结构✅ 初始化数据#x1f680; 使用…文章目录275. Java Stream API - flatMap 操作展开一对多的关系拉平你的流 背景我们为什么需要 flatMap 用 flatMap 优雅替代嵌套循环✅ 定义模型结构✅ 初始化数据 使用 flatMap 重写统计逻辑 flatMap 是如何工作的步骤 1️⃣映射map步骤 2️⃣展平flat 延伸案例Map 结构的 flatMap 小结flatMap 用法口诀 练习建议课堂可选❓ 问题下面代码的输出是什么275. Java Stream API - flatMap 操作展开一对多的关系拉平你的流 背景我们为什么需要flatMap假设我们有以下结构每个Country拥有多个City每个City有一个人口数population我们的目标是统计所有城市的总人口数。最直接的写法当然是嵌套 for 循环inttotalPopulation0;for(Countrycountry:countries){for(Citycity:country.cities()){totalPopulationcity.population();}}System.out.println(Total population totalPopulation); 输出Totalpopulation24493虽然有效但Java 8之后我们有了更优雅的方式使用流 flatMap来处理一对多的关系。 用flatMap优雅替代嵌套循环✅ 定义模型结构recordCity(Stringname,intpopulation){}recordCountry(Stringname,ListCitycities){}✅ 初始化数据CitynewYorknewCity(New York,8_258);CitylosAngelesnewCity(Los Angeles,3_821);CountryusanewCountry(USA,List.of(newYork,losAngeles));CitylondonnewCity(London,8_866);CitymanchesternewCity(Manchester,568);CountryuknewCountry(United Kingdom,List.of(london,manchester));CityparisnewCity(Paris,2_103);CitymarseillenewCity(Marseille,877);CountryfrancenewCountry(France,List.of(paris,marseille));ListCountrycountriesList.of(usa,uk,france); 使用flatMap重写统计逻辑inttotalPopulationcountries.stream().flatMap(country-country.cities().stream())// 展开所有城市.mapToInt(City::population)// 提取人口.sum();// 累加总人口System.out.println(Total population totalPopulation); 输出Totalpopulation24493flatMap是如何工作的flatMap是两个操作的组合步骤 1️⃣映射mapcountry-country.cities().stream()这一步将每个Country映射为它的城市流得到的是一个StreamStreamCity流的流。步骤 2️⃣展平flatflatMap会自动帮你把多个子流合并为一个连续的扁平流StreamCity这样你就可以对所有城市统一处理 类比图示StreamCountry---映射---StreamStreamCity|---展平flatten---StreamCity 延伸案例Map结构的flatMap假设我们有一个Continent类型它包含一个 MaprecordContinent(MapString,Countrycountries){}此时如果你想从Continent中提取所有国家可以这样写FunctionContinent,StreamCountrycontinentToCountrycontinent-continent.countries().values().stream();再进一步还可以这样嵌套flatMapinttotalcontinents.stream().flatMap(continent-continent.countries().values().stream()).flatMap(country-country.cities().stream()).mapToInt(City::population).sum(); 小结flatMap用法口诀用法场景对应方法一对一映射每个元素 → 单个新值.map()一对多映射每个元素 → 多个新值.flatMap()提取嵌套集合中的内容并扁平化.flatMap()转换成基础类型流int/long/double.mapToInt()等 练习建议课堂可选❓ 问题下面代码的输出是什么ListStringwordsList.of(java,stream,api);ListCharactercharswords.stream().flatMap(word-word.chars().mapToObj(c-(char)c)).toList();System.out.println(chars); 答案[j,a,v,a,s,t,r,e,a,m,a,p,i]

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询