stream使用案例

1.1 查找所有的偶數并求和

public?static?void?p1()?{? List<Integer> numbers = Arrays.asList(1,?2,?3,?4,?5,?6,?7,?8,?9,?10);??int?sum = numbers.stream()? ? ? .filter(num -> num %?2?==?0)? ? ? .mapToInt(Integer::intValue)? ? ? .sum() ;? System.err.printf("result: %s%n", sum) ;}

1.2?查找并打印長度大于 5 的字符串個數

public?static?void?p2() {??List<String> strings =?Arrays.asList(? ??"apple",?"banana",?"grape",?? ??"watermelon",?"kiwi",?"orange");??Long?count = strings.stream()? ? ? .filter(str -> str.length() >?5)? ? ? .count() ;??System.err.printf("result: %s%n", count) ;}

1.3 處理每一個元素最后返回新集合???????

public?static?void?p3()?{? List<Integer> numbers = Arrays.asList(1,?2,?3,?4,?5);? List<Integer> squares = numbers.stream()? ? ? .map(num -> num * num)? ? ? .collect(Collectors.toList()) ;? System.err.printf("result: %s%n", squares) ;}

將每一個元素進行平方操作,最后返回一個新的集合。輸出結果:

result:?[1, 4, 9, 16, 25]

1.4?找出整數列表中的最大元素???????

public?static?void?p4()?{? List<Integer> numbers = Arrays.asList(10,?5,?25,?15,?30);??int?max = numbers.stream()? ? ? .mapToInt(Integer::intValue)? ? ? .max()? ? ? .getAsInt();? System.err.printf("result: %s%n", max) ;}

1.5 將列表中的所有字符串連接成一個字符串???????

public?static?void?p5() {??List<String> fruits =?Arrays.asList("apple",?"banana",?"cherry","coconut",?"apple");??String?concat =fruits.stream()? ? ? .collect(Collectors.joining()) ;??System.err.printf("result: %s%n", concat) ;}

1.6 轉成大寫再排序???????

public?static?void?p6() {??List<String> fruits =?Arrays.asList("apple",?"Banana",?"Grape",?"orange",?"kiwi");??List<String> sortedUppercase = fruits.stream()? ? ? .map(String::toUpperCase)? ? ? .sorted()? ? ? .collect(Collectors.toList());??System.err.printf("result: %s%n", sortedUppercase) ;}

先將字符串轉為大寫,然后在進行排序,輸出結果:

result:?[APPLE, BANANA, GRAPE, KIWI, ORANGE]

1.7 計算double類型平均值???????

public?static?void?p7()?{? List<Double> doubles = Arrays.asList(1.0,?2.0,?3.0,?4.0,?5.0);??double?average = doubles.stream()? ? ? .mapToDouble(Double::doubleValue)? ? ? .average()? ? ? .getAsDouble() ;? System.err.printf("result: %s%n", average) ;}

1.8 刪除重復元素???????

public?static?void?p8() {??List<String> words =?Arrays.asList("apple",?"banana",?"apple",?"orange",?"banana",?"kiwi");??List<String> uniqueWords = words.stream()? ? ? .distinct()? ? ? .collect(Collectors.toList()) ;??System.err.printf("result: %s%n", uniqueWords) ;}

1.9 檢查所有元素是否符合條件???????

public?static?void?p9() {??List<Integer> numbers =?Arrays.asList(2,?4,?6,?8,?10);??boolean?allEven = numbers.stream()? ? ? .allMatch(n -> n%2?==?0) ;??System.err.printf("result: %s%n", allEven) ;}

1.10 檢查集合中是否包含特定元素???????

public?static?void?p10()?{? List<Integer> numbers = Arrays.asList(2,?4,?6,?8,?10);? boolean exists = numbers.stream()? ? ? .anyMatch(n -> n.equals(8)) ;? System.err.printf("result: %s%n", exists) ;}

1.11 查找流中最長的字符串???????

public?static?void?p11() {??List<String> fruits =?Arrays.asList("apple",?"banana",?"cherry",?"coconut",?"apple") ;? int max = fruits.stream()? ? .mapToInt(String::length)? ? .max()? ? .getAsInt() ;??System.err.printf("result: %s%n", max) ;}

1.12 從流中刪除null值???????

public?static?void?p12() {??List<String> fruits =?Arrays.asList("apple",?"banana",?"cherry",?null,"coconut",?"apple");??List<String> nonNullValues = fruits.stream()? ? ? .filter(Objects::nonNull)? ? ? .collect(Collectors.toList()) ;??System.err.printf("result: %s%n", nonNullValues) ;}

過濾為null的值,輸出結果:

result:?[apple, banana, cherry, coconut, apple]

1.13 分組并查找最大值???????

public?static?void?p13() {??List<Employee> employees =new?ArrayList<>() ;? employees.add(new?Employee("Alice","HR",50000.0)) ;? employees.add(new?Employee("Bob","IT",60000.0)) ;? employees.add(new?Employee("Charlie","Finance",55000.0)) ;? employees.add(new?Employee("David","IT",70000.0)) ;? employees.add(new?Employee("Eva",?"HR",?45000.0)) ;? employees.add(new?Employee("Frank","Finance",58000.0));??Map<String,?Optional<Employee>> highestSalaryPerDept = employees.stream()? ? ? .collect(Collectors.groupingBy(? ? ? ? ??Employee::getDepartment,?? ? ? ? ??Collectors.maxBy(Comparator.comparingDouble(Employee::getSalary))? ? ? ));? highestSalaryPerDept.forEach((key, value) -> {? ??System.err.printf("部門: %s, \t最高薪: %s%n", key, value.get()) ;? });}

輸出結果:

圖片

2.14 查找列表中第二小的元素???????

public?static?void?p14()?{? List<Integer> numbers = Arrays.asList(2,?4,?6,?8,?10) ;? Optional<Integer> secondSmallest = numbers.stream()? ? ? .distinct()? ? ? .sorted()? ? ? .skip(1)? ? ? .findFirst() ;? System.err.printf("result: %s%n", secondSmallest) ;}

1.15 查找兩個列表的交集???????

public?static?void?p15()?{? List<Integer> list1 = Arrays.asList(1,?2,?3,?4,?5) ;? List<Integer> list2 = Arrays.asList(4,?5,?6,?7,8) ;? List<Integer> intersection = list1.stream()? ? ? .filter(list2::contains)? ? ? .collect(Collectors.toList()) ;? System.err.printf("result: %s%n", intersection) ;}

1.16 并行處理提升性能

使用并行流可以通過BaseStream.parallel或Collection#parallelStream操作,如下計算1億個數的求和???????

public static void main(String[] args) {double[] arr = IntStream.range(0,?100_000_000)? ? ? .mapToDouble(i ->?new?Random().nextDouble() *?100000)? ? ? .toArray() ;? computeSumOfSquareRoots(arr);}
public static void computeSumOfSquareRoots(double[] arr) {double?serialSum = computeSerialSum(DoubleStream.of(arr));? System.out.println("Serial Sum: "?+ serialSum);
double?parallelSum = computeParallelSum(DoubleStream.of(arr));? System.out.println("Parallel Sum: "?+ parallelSum);}
public static double computeSerialSum(DoubleStream stream) {long?startTime = System.currentTimeMillis();double?sum = stream.reduce(0.0D, (l, r) -> l + r) ;long?endTime = System.currentTimeMillis();? System.out.println("Serial Computation Time: "?+ (endTime - startTime) +?" ms");return?sum;}
public static double computeParallelSum(DoubleStream stream) {long?startTime = System.currentTimeMillis();double?sum = stream.parallel().reduce(0, (l, r) -> l + r) ;long?endTime = System.currentTimeMillis();? System.out.println("Parallel Computation Time: "?+ (endTime - startTime) +?" ms");return?sum;}

運行結果???????

SerialComputation?Time:?73?msSerialSum:?5.000114159154823E12ParallelComputation?Time:?38?msParallelSum:?5.000114159151367E12

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/86577.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/86577.shtml
英文地址,請注明出處:http://en.pswp.cn/web/86577.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

力扣 刷題(第七十一天)

靈感來源 - 保持更新&#xff0c;努力學習 - python腳本學習 4的冪 解題思路 位運算條件&#xff1a;4 的冪的二進制表示中只有一個 1&#xff0c;且位于奇數位&#xff08;如 4 100&#xff0c;4 10000&#xff09;。模運算條件&#xff1a;4 的冪減 1 后能被 3 整除&…

深度學習使用Pytorch訓練模型步驟

訓練模型是機器學習和深度學習中的核心過程&#xff0c;旨在通過大量數據學習模型參數&#xff0c;以便模型能夠對新的、未見過的數據做出準確的預測。 訓練模型通常包括以下幾個步驟&#xff1a; 1.數據準備&#xff1a; 收集和處理數據&#xff0c;包括清洗、標準化和歸一化…

Unity_導航操作(鼠標控制人物移動)_運動動畫

文章目錄 前言一、Navigation 智能導航地圖烘焙1.創建Plan和NavMesh Surface2.智能導航地圖烘焙 二、MouseManager 鼠標控制人物移動1.給場景添加人物&#xff0c;并給人物添加導航組件2.編寫腳本管理鼠標控制3.給人物編寫腳本&#xff0c;訂閱事件&#xff08;添加方法給Mouse…

6. 接口分布式測試pytest-xdist

pytest-xdist實戰指南&#xff1a;解鎖分布式測試的高效之道 隨著測試規模擴大&#xff0c;執行時間成為瓶頸。本文將帶你深入掌握pytest-xdist插件&#xff0c;利用分布式測試將執行速度提升300%。 一、核心命令解析 加速安裝&#xff08;國內鏡像&#xff09; pip install …

預訓練語言模型

預訓練語言模型 1.1Encoder-only PLM ? Transformer結構主要由Encoder、Decoder組成&#xff0c;根據特點引入了ELMo的預訓練思路。 ELMo&#xff08;Embeddings from Language Models&#xff09;是一種深度上下文化詞表示方法&#xff0c; 該模型由一個**前向語言模型&…

Altera PCI IP target設計分享

最近調試也有關于使用Altera 家的PCI IP&#xff0c;然后分享一下代碼&#xff1a; 主要實現&#xff1a;主控作為主設備&#xff0c;FPGA作為從設備&#xff0c;主控對FPGA IO讀寫的功能 后續會分享FPGA作為主設備&#xff0c; 從 FPGA通過 memory寫到主控內存&#xff0c;會…

基于機器學習的智能文本分類技術研究與應用

在當今數字化時代&#xff0c;文本數據的爆炸式增長給信息管理和知識發現帶來了巨大的挑戰。從新聞文章、社交媒體帖子到企業文檔和學術論文&#xff0c;海量的文本數據需要高效地分類和管理&#xff0c;以便用戶能夠快速找到所需信息。傳統的文本分類方法主要依賴于人工規則和…

前端項目3-01:登錄頁面

一、效果圖 二、全部代碼 <!DOCTYPE html> <html><head><meta charset"utf-8"><title>碼農魔盒</title><style>.bg{position: fixed;top: 0;left:0;object-fit: cover;width: 100vw;height: 100vh;}.box{width: 950px;he…

Nexus CLI:簡化你的分布式計算貢獻之旅

探索分布式證明網絡的力量&#xff1a;Nexus CLI 項目深入解析 在今天的數字時代&#xff0c;分布式計算和去中心化技術正成為互聯網發展的前沿。Nexus CLI 是一個為 Nexus 網絡提供證明的高性能命令行界面&#xff0c;它不僅在概念上先進&#xff0c;更是在具體實現中為開發者…

IBW 2025: CertiK首席商務官出席,探討AI與Web3融合帶來的安全挑戰

6月26日至27日&#xff0c;全球最大的Web3安全公司CertiK亮相伊斯坦布爾區塊鏈周&#xff08;IBW 2025&#xff09;&#xff0c;首席商務官Jason Jiang出席兩場圓桌論壇&#xff0c;分享了CertiK在AI與Web3融合領域的前沿觀察與安全見解。他與普華永道土耳其網絡安全服務主管Nu…

Vivado 五種仿真類型的區別

Vivado 五種仿真類型的區別 我們還是用“建房子”的例子來類比。您已經有了“建筑藍圖”&#xff08;HLS 生成的 RTL 代碼&#xff09;&#xff0c;現在要把它建成真正的房子&#xff08;FPGA 電路&#xff09;。這五種仿真就是在這個過程中不同階段的“質量檢查”。 1. 行為…

小程序快速獲取url link方法,短信里面快速打開鏈接

獲取小程序鏈接方法 uni.request({url:https://api.weixin.qq.com/cgi-bin/token?grant_typeclient_credential&appidwxxxxxxxxxxxx&secret111111111111111111111111111111111,method:GET,success(res) {console.log(res.data)let d {"path": "/xxx/…

Spring 框架(1-4)

第一章&#xff1a;Spring 框架概述 1.1 Spring 框架的定義與背景 Spring 是一個開源的輕量級 Java 開發框架&#xff0c;于 2003 年由 Rod Johnson 創立&#xff0c;旨在解決企業級應用開發的復雜性。其核心設計思想是面向接口編程和松耦合架構&#xff0c;通過分層設計&…

RabitQ 量化:既省內存又提性能

突破高維向量內存瓶頸:Mlivus Cloud RaBitQ量化技術的工程實踐與調優指南 作為大禹智庫高級研究員,擁有三十余年向量數據庫與AI系統架構經驗的我發現,在當今多模態AI落地的核心場景中,高維向量引發的內存資源消耗問題已成為制約系統規模化部署的“卡脖子”因素。特別是在大…

創客匠人:創始人 IP 打造的得力助手

在當今競爭激烈的商業環境中&#xff0c;創始人 IP 的打造對于企業的發展愈發重要。一個鮮明且具有影響力的創始人 IP&#xff0c;能夠為企業帶來獨特的競爭優勢&#xff0c;提升品牌知名度與美譽度。創客匠人在創始人 IP 打造過程中扮演著不可或缺的角色&#xff0c;為創始人提…

如何為虛擬機上的 Manjaro Linux啟用 VMware 拖放功能

如果你的Manjaro 發行版本是安裝在 VMware Workstation Player 上使用的 &#xff0c;而且希望可以通過拖放功能將文件或文件夾從宿主機復制到客戶端的Manjaro 里面&#xff0c;那么可以按照以下的步驟進行操作&#xff0c;開啟拖放功能。 在 VMware 虛擬機上安裝 Manjaro 后&…

【C/C++】單元測試實戰:Stub與Mock框架解析

C 單元測試中的 Stub/Mock 框架詳解 在單元測試中&#xff0c;Stub&#xff08;打樁&#xff09;和Mock都是替代真實依賴以簡化測試的技術。通常&#xff0c;Stub&#xff08;或 Fake&#xff09;提供了一個簡化實現&#xff0c;用于替代生產代碼中的真實對象&#xff08;例如…

工廠 + 策略設計模式(實戰教程)

在軟件開發中&#xff0c;設計模式是解決特定問題的通用方案&#xff0c;而工廠模式與策略模式的結合使用&#xff0c;能在特定業務場景下發揮強大的威力。本文將基于新增題目&#xff08;題目類型有單選、多選、判斷、解答&#xff09;這一業務場景&#xff0c;詳細闡述如何運…

Nuxt3中使用 Ant-Design-Vue 的BackTop 組件實現自動返回頁面頂部

在現代 Web 應用中&#xff0c;提供一個方便用戶返回頁面頂部的功能是非常重要的。Ant Design Vue 提供了 BackTop 組件&#xff0c;可以輕松實現這一功能。本文將詳細介紹如何在 Nuxt 3 項目中使用 <a-back-top/> 組件&#xff0c;并通過按需引入的方式加載組件及其樣式…

在統信UOS(Linux)中構建SQLite3桌面應用筆記

目錄 1 下載lazarus 2 下載sqlite3源碼編譯生成庫文件 3 新建項目 4 設置并編譯 一次極簡單的測試&#xff0c;記錄一下。 操作系統&#xff1a;統信UOS&#xff0c; 內核&#xff1a;4.19.0-arm64-desktop 處理器&#xff1a;D3000 整個流程難點是生成so庫文件并正確加…