JDK8之Stream新特性

/***JDK8  Stream特性* Created by chengbx on 2018/5/27.* Java 8 中的 Stream 是對集合(Collection)對象功能的增強,它專注于對集合對象進行各種非常便利、高效的聚合操作(aggregate operation),* 或者大批量數據操作 (bulk data operation)。Stream API 借助于同樣新出現的 Lambda 表達式,極大的提高編程效率和程序可讀性。* 同時它提供串行和并行兩種模式進行匯聚操作,并發模式能夠充分利用多核處理器的優勢,使用 fork/join 并行方式來拆分任務和加速處理過程。* 通常編寫并行代碼很難而且容易出錯, 但使用 Stream API 無需編寫一行多線程的代碼,就可以很方便地寫出高性能的并發程序。* 所以說,Java 8 中首次出現的 java.util.stream 是一個函數式語言+多核時代綜合影響的產物。*  一、Stream API 的操作步驟:*        * 1. 創建 Stream** 2. 中間操作** 3. 終止操作(終端操作)** 4.   接口中的默認方法*      接口默認方法的”類優先”原則*      若一個接口中定義了一個默認方法,而另外一個父類或接口中*      又定義了一個同名的方法時*      1.選擇父類中的方法。如果一個父類提供了具體的實現,那么*      接口中具有相同名稱和參數的默認方法會被忽略.*      2.接口沖突。如果一個父接口提供一個默認方法,而另一個接*      口也提供了一個具有相同名稱和參數列表的方法(不管方法*      是否是默認方法),那么必須覆蓋該方法來解決沖突* 5.   新增的重復注解@Repeatble和類型注解*         java8新增了重復注解,其使用方式為:@Repeatable(Authorities.class)public @interface Authority {String role();}public @interface Authorities {Authority[] value();}public class RepeatAnnotationUseNewVersion {@Authority(role="Admin")@Authority(role="Manager")publicvoiddoSomeThing(){ }}2.Java8為ElementType枚舉增加了TYPE_PARAMETER、TYPE_USE兩個枚舉值,從而可以使用@Target(ElementType_TYPE_USE)修飾注解定義,這種注解被稱為類型注解,可以用在任何使用到類型的地方*/
public class TestStream {List<Employee> employees = Arrays.asList(new Employee("aaa",11,5000),new Employee("bbb",21,5200),new Employee("ccc",13,5500),new Employee("ddd",54,6400),new Employee("eee",16,7100),new Employee("fff",74,7120),new Employee("ggg",12,7150));/*** 創建stream*/@Testpublic void test1(){//1. Collection 提供了兩個方法  stream() 與 parallelStream()List<String> list = new ArrayList<>();Stream<String> stream =  list.stream();Stream<String> parallelStream = list.parallelStream(); //獲取一個并行流//2. 通過 Arrays 中的 stream() 獲取一個數組流Integer[] nums = new Integer[10];Stream<Integer> stream1 = Arrays.stream(nums);//3. 通過 Stream 類中靜態方法 of()Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6);//4. 創建無限流//迭代Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10);stream3.forEach(System.out::println);//生成Stream<Double> stream4 = Stream.generate(Math::random).limit(2);stream4.forEach(System.out::println);}/*篩選與切片filter——接收 Lambda , 從流中排除某些元素。limit——截斷流,使其元素不超過給定數量。skip(n) —— 跳過元素,返回一個扔掉了前 n 個元素的流。若流中元素不足 n 個,則返回一個空流。與 limit(n) 互補distinct——篩選,通過流所生成元素的 hashCode() 和 equals() 去除重復元素*///內部迭代:迭代操作 Stream API 內部完成
    @Testpublic void test2(){//中間操作,不會執行任何操作Stream<Employee> str = employees.stream().filter((e) -> e.getAge()>30).limit(1);//終止操作,一次性執行全部內容,即"惰性求值"
        str.forEach(System.out::println);// employees.stream().filter((e) -> e.getAge()<30)//            .forEach((employee) -> System.out.println(employee));
    }//外部迭代
    @Testpublic void test3(){Iterator<Employee> it = employees.iterator();while(it.hasNext()){System.out.println(it.next());}}@Testpublic void test4(){employees.stream().filter((e) -> {System.out.println("短路!"); // &&  ||return e.getSalary() >= 5000;}).limit(3).forEach(System.out::println);}@Testpublic void test5(){employees.parallelStream().filter((e) -> e.getSalary() >= 5000).skip(2).forEach(System.out::println);}@Testpublic void test6(){employees.stream().distinct().forEach(System.out::println);}/*** 映射* map -接收lambda,將元素轉換成其他形式獲取信息,接收一個函數作為參數,該函數會被應用在每個元素上,并將其映射成一個新的元素。* flatmap-接收一個函數作為參數,將流中的每個值都換成另一個流,然后把所有流連接成一個流*/@Testpublic void test7(){List<String> list = Arrays.asList("aaa","bbb","ccc","ddd");list.stream().map((str) -> str.toUpperCase()).forEach((str) -> System.out.println(str));System.out.println("---------------");employees.stream().map(Employee::getName).forEach((name) ->System.out.println(name));}/*** 排序* sorted()--自然排序(comparable)* sorted(Comparator com)--定制排序(Comparator)*/@Testpublic void test8(){List<String> list = Arrays.asList("eee","ggg","ccc","ddd");list.stream().sorted().forEach(System.out::println);System.out.println("-------------------以下是定制排序-------------");employees.stream().sorted((e1,e2) ->{if (e1.getAge() ==e2.getAge()) {return e1.getName().compareTo(e2.getName());}else{return Integer.compare(e1.getAge(),e2.getAge());}}).forEach((employee) -> System.out.println(employee));}//3. 終止操作/*allMatch——檢查是否匹配所有元素anyMatch——檢查是否至少匹配一個元素noneMatch——檢查是否沒有匹配的元素findFirst——返回第一個元素findAny——返回當前流中的任意元素count——返回流中元素的總個數max——返回流中最大值min——返回流中最小值注意:流進行了終止操作后,不能再次使用*/@Testpublic void test9(){boolean b = employees.stream().allMatch((emp) -> emp.getAge()==15);System.out.println(b);System.out.println("---------------");boolean b1 = employees.stream().anyMatch((emp) -> emp.getAge()==15);System.out.println(b1);System.out.println("---------------");boolean b2 = employees.stream().noneMatch((emp) -> emp.getAge()==15);System.out.println(b2);System.out.println("---------------");Optional<Employee> optional = employees.stream().sorted((emp1, emp2) -> Double.compare(emp1.getSalary(),emp2.getSalary())).findFirst();System.out.println(optional.get());System.out.println("---------------");Optional<Employee> optional1 = employees.parallelStream().filter((emp) -> emp.getAge() >15).findAny();System.out.println(optional1);System.out.println("---------------");Long count = employees.parallelStream().filter((emp) -> emp.getAge() >15).count();System.out.println(count);Optional<Double> optiona3 = employees.stream().map((emp) -> emp.getSalary()).max(Double::compareTo);System.out.println(optiona3.get());System.out.println("---------------");Optional<Employee> optiona4 = employees.stream().min((e1,e2) ->Double.compare(e1.getSalary(),e2.getSalary()));System.out.println(optiona4);}/*** 歸約reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以將流中元素反復結合起來,得到一個值。*/@Testpublic void test10(){List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);Integer sum = list.stream().reduce(0,(x,y) -> x+y);System.out.println(sum);//55System.out.println("---------------------");Optional<Double> sumSal = employees.stream().map(Employee::getSalary).reduce(Double::sum);System.out.println(sumSal);}/*** 收集:* collect——將流轉換為其他形式。接收一個 Collector接口的實現,用于給Stream中元素做匯總的方法*///將employee集合中name值取出來放入集合中 aaa bbb ccc ddd eee fff ggg
    @Testpublic void test11(){List list = employees.stream().map(Employee::getName).collect(Collectors.toList());list.forEach(System.out::println);}@Testpublic void test12(){Set set = employees.stream().map(Employee::getName).collect(Collectors.toSet());set.forEach(System.out::println);}@Testpublic void test13(){HashSet hashSet = employees.stream().map(Employee::getName).collect(Collectors.toCollection(HashSet::new));hashSet.forEach(System.out::println);}//獲取集合中元素的個數  7
    @Testpublic void test14(){long count =  employees.stream().collect(Collectors.counting());System.out.println(count);System.out.println("----------------");//獲取工資平均值Double avgMoney = employees.stream().collect(Collectors.averagingDouble((emp) -> emp.getSalary()));System.out.println(avgMoney);//6210.0System.out.println("----------------");//工資總和Double sumMoney = employees.stream().collect(Collectors.summingDouble(Employee::getSalary));System.out.println(sumMoney);//最大值Optional<Employee> optional= employees.stream().collect(Collectors.maxBy((emp1,emp2) -> Double.compare(emp1.getSalary(),emp2.getSalary())));System.out.println(optional.get());//Employee{name='ggg', age=12, salary=7150.0}//最小值Optional<Double> minMoney = employees.stream().map(Employee::getSalary).collect(Collectors.minBy(Double::compare));System.out.println(minMoney.get());}//分組
    @Testpublic void test15(){employees.stream().collect(Collectors.groupingBy(Employee::getAge));}//分區
    @Testpublic  void test16(){Map<Boolean,List<Employee>> map =employees.stream().collect(Collectors.partitioningBy((e) -> e.getSalary() >6000));System.out.println(map);//{false=[Employee{name='aaa', age=11, salary=5000.0}, Employee{name='bbb', age=21, salary=5200.0},// Employee{name='ccc', age=13, salary=5500.0}],// true=[Employee{name='ddd', age=54, salary=6400.0}, Employee{name='eee', age=16, salary=7100.0},// Employee{name='fff', age=74, salary=7120.0}, Employee{name='ggg', age=12, salary=7150.0}]}
}@Testpublic void test17(){DoubleSummaryStatistics dss =employees.stream().collect(Collectors.summarizingDouble(Employee::getSalary));//求平均值
        System.out.println(dss.getAverage());//求最大值
        System.out.println(dss.getMax());//求和
        System.out.println(dss.getSum());}    @Testpublic void test18(){String name = employees.stream().map(Employee::getName).collect(Collectors.joining(","));System.out.println(name);//aaa,bbb,ccc,ddd,eee,fff,ggg
    }
}

?

轉載于:https://www.cnblogs.com/cbxBlog/p/9123106.html

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

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

相關文章

雞蛋學運維-2:Rsync同步配置步驟

說明&#xff1a;系統環境CentOS release 6.5 (Final) 2.6.32-431.el6.x86_64rsync server:配置步驟1、vi /etc/rsyncd.conf#Rsync server#created by lijianfeng 18:26 2017-9-24#rsyncd.conf start#uid rsyncgid rsyncuse chroot nomax connections 2000timeout 600pid…

IntelliJ IDEA代碼分屏顯示

轉載于:https://www.cnblogs.com/EasonJim/p/9124809.html

vscode重置應用程序_如何在Windows 10上重置應用程序的數據

vscode重置應用程序With Windows 10’s Anniversary Update, you can now reset an app’s data without actually uninstalling and reinstalling the app. This can fix problems when an app has gotten into a bad state, or just quickly restore an app to its default s…

程序報錯與提示

2019獨角獸企業重金招聘Python工程師標準>>> 我們在開發中, 為了程序的規范性,把報錯級別,調的比較高NOTICE級別的也報出來,有助于我們快速定位錯誤和代碼規范&#xff0c;但是,在產品上線后,網站運營過程中,就不宜報這么多錯. 1:這種錯誤給客戶的印象不好 2:在報錯…

【codevs1230】元素查找

problem 給出n個正整數&#xff0c;然后有m個詢問詢問該整數是否在n個正整數中出現過solution 哈希表&#xff1f; 當然是set水洛 codes #include<iostream> #include<set> using namespace std; set<int>s; int main(){int n, m;cin>>n>>m;for…

dock怎么自定義_如何自定義和調整Mac的Dock

dock怎么自定義The macOS dock normally appears at the bottom of your screen, but it doesn’t have to. The dock is customizable in quite a few ways you might not be aware of, especially if you’re a new Mac user. macOS塢站通常顯示在屏幕底部&#xff0c;但不是…

ios 輕掃手勢_輕掃即可快速刪除iOS計算器中的數字

ios 輕掃手勢iOS’ built-in calculator is a basic, simple-to-use calculator that’s very handy for doing some quick calculations, such as calculating the tip on your restaurant bill. It’s also useful for longer, more complicated calculations. However, ther…

游戲安全資訊精選 2017年第十期 英國彩票網遭遇DDoS攻擊,中斷90分鐘 DNSMASQ多高危漏洞公告 阿里云協助警方破獲國內最大黑客攻擊案,攻擊峰值690G...

【本周游戲行業DDoS攻擊態勢】 國慶期間&#xff0c;針對游戲行業的DDoS攻擊放緩&#xff0c;攻擊者也在放“小長假”&#xff0c;10月8日超過500G的攻擊可視作攻擊猛烈度恢復的表現。 【游戲安全動態】 英國彩票網遭遇DDoS攻擊&#xff0c;中斷90分鐘 點擊查看原文 點評&#…

02 jmeter 簡單發送http請求

一、新建http請求模板1、測試計劃2、右鍵Threads(users)-線程組3、右鍵sample-http請求4、右鍵監聽器-查看結果樹5、右鍵監聽器-查看聚合報告二、編輯http請求內容三、設置并發用戶1&#xff1a;虛擬用戶數&#xff1b; 2&#xff1a;加載用戶時間&#xff1b;3、每個用戶循環次…

java調用siri 語言_如何更改Siri的聲音,口音,性別和語言

java調用siri 語言Most of us are familiar with Siri as an American female voice. What you may not realize is that you can actually change Siri to have a different accent, gender, and language. 我們大多數人都熟悉Siri&#xff0c;這是一種美國女性聲音。 您可能沒…

高手與菜鳥,思想與技術

這是個嚴肅的話題。同樣的問題&#xff0c;高手和菜鳥的看法是不同&#xff0c;怎么樣不同呢&#xff1f;我們是高手還菜鳥呢&#xff1f;看看以下問題&#xff1a;對于AJAX&#xff1a;菜鳥看到的是一種新技術&#xff0c;趨之若騖&#xff1b;高手看到的是javascript的一種巧…

玩轉 React(四)- 創造一個新的 HTML 標簽

在第二篇文章 《新型前端開發方式》 中有說到 React 有很爽的一點就是給我們一種創造 HTML 標簽的能力&#xff0c;那么今天這篇文章就詳細講解下 React 是如何提供這種能力的&#xff0c;作為前端開發者如何來運用這種能力。 在第三篇文章 《JavaScript代碼里寫HTML一樣可以很…

mac word 設置語言_如何更改Mac的語言和區域設置

mac word 設置語言If you want to use your Mac in a different language, or you’re live in a different region, then you can change it in OS X. When you do, it’ll display everything in your preferred language, currency, date format, and more. 如果您想以其他語…

【Luogu3931】SAC E#1 - 一道難題 Tree

problem solution codes //樹形DP //f[u]:割掉u和u子樹中所有的葉子節點所需要的最小代價 #include<iostream> #include<vector>using namespace std; typedef long long LL; const int N (int)1e510, inf 1e9;int n, S;struct node{LL to, v;node(LL to, LL v):…

IT史上十大收購案

本文講的是IT史上十大收購案【IT168 資訊】據英國資訊網站V3報道&#xff0c;本周&#xff0c;業界中的大事件無疑是硬件巨頭Intel公司斥資76.8億美元全盤收購著名安全軟件公司McAfee。本次收購被看做是軟硬件領域的一次親密接觸&#xff0c;下面為大家盤點近年來IT領域中影響較…

飛利浦dicom_如何按計劃打開或關閉飛利浦色相燈

飛利浦dicomThe Philips Hue app can do a handful of cool stuff with your Hue lights, including the ability to schedule your lights to turn on and off at specific times throughout the day. Here’s how to set it up so that you never have to flip a switch ever…

Mono生命周期小實驗

今天在寫代碼的時候&#xff0c;遇到一個初始化順序問題&#xff0c;于是做了一個實驗&#xff0c;下面記錄結果&#xff1a; 情景&#xff1a; 1.在 腳本A中實例化 一個預制體&#xff0c;該預制體掛有腳本B 2.在 腳本A中&#xff0c;獲取實例化物體 身上的 腳本B&#xff0c;…

[讀書筆記]大型分布式網站架構設計與實踐.分布式緩存

前言&#xff1a;本書是對分布式系統架構涉及到的相關技術的一本科普書籍。由于很難作為開發參考&#xff0c;只能但求了解。所以通篇淺讀&#xff0c;對分布式系統進行大致的了解。因為寫的非常好&#xff0c;感覺非常有意思&#xff0c;自己也做不出總結。所謂的讀書筆記也就…

寧波保哥后院_如何拋出終極后院電影之夜

寧波保哥后院Most people have the basics of throwing a movie night down: you get a movie, you get snacks, you get comfortable, and boom, you’re done. When it comes to throwing a movie party in the backyard, however, things get a little trickier. Read on as…

大廠前端高頻面試問題與答案精選

近日&#xff0c;GitHub上一位名為木易楊&#xff08;yygmind&#xff09;的開發者&#xff0c;在 GitHub 中建了一個名為Advanced-Frontend/Daily-Interview-Question項目&#xff0c;該項目每天會更新一道前端大廠面試題&#xff0c;并邀請開發者在issue區中作答&#xff0c;…