摘要:一創(chuàng)建里流的四種方式第一種通過得方法串行流或者方法并行流創(chuàng)建。終止操作時(shí)一次性全部處理,稱為延遲加載篩選切片過濾中建操作。終止操作只有執(zhí)行終止操作才會執(zhí)行全部。即延遲加載結(jié)果中建操作。截?cái)嗔?,使其元素不超過給定數(shù)量。返回流中最大值。
Stream api
**Stream api 是java8 中提供的對集合處理的api , 對數(shù)據(jù)進(jìn)行一系列的中間操作,元數(shù)據(jù)不會發(fā)生改變 集合講的是數(shù)據(jù), 流 講的是計(jì)算(用于操作數(shù)據(jù)源,集合,數(shù)組)所生成的元素序列。** Stream API位于 java.util.stream.* 包下。
一 創(chuàng)建里Stream 流的四種方式1 Stream 自己不會存儲元素
2 Stream 不會改變源對象。相反,他們會返回一個持有結(jié)果的性Sstream 。 3 Stream 操作是延遲執(zhí)行的。這以為這他們會等到需要結(jié)果的時(shí)候才執(zhí)行(延遲加載)。
### 1 第一種 通過Collection得Stream()方法(串行流)或者 parallelStream()方法(并行流)創(chuàng)建Stream。
Listlist = Arrays.asList("1","2","3","4","0","222","33"); Stream stream = list.stream(); Stream stream1 = list.parallelStream();
### 2 通過Arrays中得靜態(tài)方法stream()獲取數(shù)組流
IntStream stream = Arrays.stream(new int[]{1,2,3});
### 3 通過Stream類中得 of()靜態(tài)方法獲取流
Streamstream = Stream.of("a","b","c");
### 4 創(chuàng)建無限流(迭代、生成)
//迭代(需要傳入一個種子,也就是起始值,然后傳入一個一元操作) Stream二 Stream 中間操作stream1 = Stream.iterate(2, (x) -> x * 2); //生成(無限產(chǎn)生對象) Stream stream2 = Stream.generate(() -> Math.random());
1 篩選切片多個中間操作可以連接起來形成一個流水線,除非流水線終止操作,否則中間操作不會執(zhí)行任何處理。 終止操作時(shí)一次性全部處理,稱為“延遲加載”
Listlist = Arrays.asList("1","2","3","4","0","222","33"); Stream stream = list.stream().filter((x) -> { System.out.println(" api 中建操作。"); return x.equals("3"); }); //終止操作:只有執(zhí)行終止操作才會執(zhí)行全部。即:延遲加載 stream.forEach(System.out::println);
結(jié)果
api 中建操作。 api 中建操作。 api 中建操作。 3 api 中建操作。 api 中建操作。 api 中建操作。 api 中建操作。
List3 skip(n) 跳過元素list = Arrays.asList("1","2","3","4","0","222","33","3","3"); Stream stream = list.stream().filter((x) -> { System.out.println(" api 中建操作。"); return x.equals("3"); }); //取兩個 , 可以配合其他得中間操作,并截?cái)嗔鳎〉较鄳?yīng)的元素個數(shù),這不會往下執(zhí)行,可以提高效率 stream.limit(2).forEach(System.out::println);
skip(n),返回一個扔掉了前n個元素的流。若流中元素不足n個,則返回一個空,與limit(n)互補(bǔ)。
List4 篩選list = Arrays.asList("1","2","3","4","0","222","33","3","3"); Stream stream = list.stream().filter((x) -> { System.out.println(" api 中建操作。"); return x.equals("3"); }); //skip(n),返回一個扔掉了前n個元素的流。若流中元素不足n個,則返回一個空,與limit(n)互補(bǔ)。 stream.skip(3).limit(1).forEach(System.out::println);
distinct 通過流所生成元素的hashCode()和equals()去除重復(fù)元素
Listlist = Arrays.asList("1","2","3","4","0","222","33","3","3"); Stream stream = list.stream(); stream.distinct().forEach(System.out::println);
1 2 3 4 0 222 335 映射
map - 接受lambda 將元素轉(zhuǎn)換為其他形式或提取信息。
接受一個函數(shù)作為參數(shù),該函數(shù)會被應(yīng)用到每個元素上,并將其映射成一個新元素
flatMap 接受一個函數(shù)作為參數(shù),將流中的每個值都轉(zhuǎn)成另一個流,然后把所有流連成一個流。
List6 排序stuList = Arrays.asList(new Stu("a",1),new Stu("ab",3),new Stu("c",11),new Stu("f",12)); Stream stream = stuList.stream(); //去除list中所有的年齡 stream.map(Stu::getAge).forEach(System.out::println); //把所有年齡再返回一個集合 List collect = stream.map(Stu::getAge).collect(Collectors.toList()); stream.flatMap(stu -> test1.filterCharacter(stu.getName())).forEach(System.out::println);
sorted有兩種方法,一種是不傳任何參數(shù),叫自然排序,還有一種需要傳Comparator 接口參數(shù),叫做定制排序。
//自然排序 Listcollect = list.stream().sorted().collect(Collectors.toList()); List collect2 = list.stream().sorted((o1, o2) -> { if(o1.length()>o2.length()){ return 1; }else if(o1.length() 三 Stream 終止操作 實(shí)體類
public class Person { String name ; String sex ; int age; Status statusEnum; public Person(String name, String sex, int age, Status statusEnum) { this.name = name; this.sex = sex; this.age = age; this.statusEnum = statusEnum; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Status getStatusEnum() { return statusEnum; } public void setStatusEnum(Status statusEnum) { this.statusEnum = statusEnum; } @Override public String toString() { return "Person{" + "name="" + name + """ + ", sex="" + sex + """ + ", age=" + age + ", statusEnum=" + statusEnum + "}"; } }操作List1 查找與匹配persons = Arrays.asList( new Person("張三", "男", 76, Status.FREE), new Person("李四", "女", 12, Status.BUSY), new Person("王五", "男", 35, Status.BUSY), new Person("趙六", "男", 3, Status.FREE), new Person("錢七", "男", 56, Status.BUSY), new Person("翠花", "女", 34, Status.VOCATION), new Person("翠花", "女", 34, Status.FREE), new Person("翠花", "女", 34, Status.VOCATION) ); ##### 1 allMatch —— 檢查是否匹配所有元素。
public void test1(){ boolean allMatch = persons.stream().allMatch((x) -> { return x.getStatusEnum().equals(Status.FREE); }); System.out.println(allMatch); }2 anyMatch —— 檢查是否至少匹配一個元素。
public void test2(){ boolean allMatch = persons.stream().anyMatch((x) -> { return x.getStatusEnum().equals(Status.FREE); }); System.out.println(allMatch); }3 noneMatch —— 檢查是否沒有匹配所有元素。
檢查 所有的是否都是 FREE ----- 結(jié)果是falsepublic void test3(){ boolean allMatch = persons.stream().noneMatch((x) -> { return x.getStatusEnum().equals(Status.FREE); }); System.out.println(allMatch); }4 findFirst —— 返回第一個元素。
public void test4(){ Optionalfirst = persons.stream().findFirst(); System.out.println(first.get()); } ##### 5 findAny —— 返回當(dāng)前流中任意元素。
public void test5(){ Optionalfirst = persons.stream().findAny(); //first.orElse(new Person()); 如果沒空 可以穿一個新的對象去代替它 System.out.println(first.get()); } ##### 6 count —— 返回流中元素總個數(shù)。
public void test6(){ long first = persons.stream().count(); System.out.println(first); }##### 7 max —— 返回流中最大值。
public void test7(){ Optionalperson = persons.stream().max((x,y) -> Integer.compare(x.age, y.age)); System.out.println(person.get()); } ##### 8 min —— 返回流中最小值。
public void test8(){ Optional2 歸約 : 可以將流中元素反復(fù)結(jié)合在一起,得到一個值person = persons.stream().min((x,y) -> Integer.compare(x.age, y.age)); System.out.println(person.get()); } 1 reduce(T identitty,BinaryOperator)首先,需要傳一個起始值,然后,傳入的是一個二元運(yùn)算。
public void test9(){ Listlist = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // identitty 起始值 0 然后與集合中的值進(jìn)行 相應(yīng)的運(yùn)算,再次賦值給 identity 然后 在進(jìn)行運(yùn)算。 Integer sum = list.stream().reduce(0, (x, y) -> x + y); System.out.println(sum); } ##### 2 reduce(BinaryOperator)此方法相對于上面方法來說,沒有起始值,則有可能結(jié)果為空,所以返回的值會被封裝到Optional中。
map和reduce的連接通常稱為map-reduce模式,因Google用它來進(jìn)行網(wǎng)絡(luò)搜索而出名。 用map 來提取 對象中某個屬性,然后再用reduce 進(jìn)行歸約。public void test10() { Optionalreduce = persons.stream().map(Person::getAge).reduce(Integer::sum); System.out.println(reduce.get()); } 3 收集 : 收集collect(將流轉(zhuǎn)換為其他形式。接收一個Collector接口得實(shí)現(xiàn),用于給其他Stream中元素做匯總的方法)
Collector接口中方法得實(shí)現(xiàn)決定了如何對流執(zhí)行收集操作(如收集到List,Set,Map)。 但是Collectors實(shí)用類提供了很多靜態(tài)方法,可以方便地創(chuàng)建常見得收集器實(shí)例。1 Collectors.toList() 將流轉(zhuǎn)換成List
public void test11() { Listcollect = persons.stream().collect(Collectors.toList()); collect.forEach(System.out::println); } ###### 2 將流轉(zhuǎn)換成HashSet
public void test12() { //hashset會去重復(fù) Setcollect = persons.stream().map(Person::getName).collect(Collectors.toSet()); collect.forEach(System.out::println); } ###### 3 將流轉(zhuǎn)換成其他集合
public void test13() { Setcollect = persons.stream().map(Person::getAge).collect(Collectors.toCollection(LinkedHashSet::new)); collect.forEach(System.out::println); } ##### 4 Collectors.counting() 元素個數(shù)
public void test14() { Long collect = persons.stream().map(Person::getAge).collect(Collectors.counting()); System.out.println(collect); }##### 5 將流轉(zhuǎn)換為其他形式 , 接受一個conllectors接口的實(shí)現(xiàn),用于給Stream中元素做匯總的方法
public void test14s() { // 1 對元素進(jìn)行匯總方法 DoubleSummaryStatistics collect = persons.stream().collect(Collectors.summarizingDouble(Person::getAge)); IntSummaryStatistics collect2 = persons.stream().collect(Collectors.summarizingInt(Person::getAge)); System.out.println(collect.getMax()); System.out.println(collect.getAverage()); System.out.println(collect.getCount()); System.out.println(collect.getMin()); System.out.println(collect.getSum());###### 2 講元素轉(zhuǎn)換為其他形式
String collect1 = persons.stream().map(Person::getName).collect(Collectors.joining(",","頭","尾")); String collect3 = persons.stream().map(Person::getName).collect(Collectors.joining()); System.out.println(collect1); //頭張三,李四,王五,趙六,錢七,翠花,翠花,翠花尾 System.out.println(collect3); // 張三李四王五趙六錢七翠花翠花翠花 }1. Collectors.averagingDouble() 2 Collectors.averagingDouble() 3 Collectors.averagingLong() 平均數(shù),這三個方法都可以求平均數(shù),不同之處在于傳入得參數(shù)類型不同,返回值都為Doublepublic void test15() { Double s = persons.stream().collect(Collectors.averagingDouble(Person::getAge)); System.out.println(s); }##### 8 Collectors.maxBy() 求最大值
public void test16() { Optionalcollect = persons.stream().collect(Collectors.maxBy((o1, o2) -> Integer.compare(o1.age, o2.age))); System.out.println(collect.get().age); } ##### 9 Collectors.minBy() 求最小值
public void test17() { Optionalcollect = persons.stream().collect(Collectors.minBy((o1, o2) -> Integer.compare(o1.age, o2.age))); System.out.println(collect.get().age); } 10 Collectors.groupingBy()分組 ,返回一個map
按照 Status 分組public void test18() { Map> collect = persons.stream().collect(Collectors.groupingBy(Person::getStatusEnum)); collect.forEach((status, people) -> { System.out.println(" status === " + status); people.forEach(System.out::println); }); } ###### 11 多級分組
Collectors.groupingBy()還可以實(shí)現(xiàn)多級分組public void test19() { Map>> collect = persons.stream().collect(Collectors.groupingBy(Person::getStatusEnum,Collectors.groupingBy(Person::getSex))); Map >> collect2 = persons.stream().collect(Collectors.groupingBy(Person::getStatusEnum,Collectors.groupingBy( e->{ if (e.getAge()>10){ return "小孩"; }else { return "大人"; } } ))); System.out.println(collect); System.out.println(collect2); } ##### 12 分區(qū)
Collectors.partitioningBy() 分區(qū),參數(shù)中傳一個函數(shù),返回true,和false 分成兩個區(qū) public void test20() { 年齡大于39的分區(qū) 不滿足再的分區(qū)Map> collect = persons.stream().collect(Collectors.groupingBy(e -> e.getAge() > 30)); System.out.println(collect); }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/75143.html
摘要:數(shù)據(jù)流教程原文譯者飛龍協(xié)議這個示例驅(qū)動的教程是數(shù)據(jù)流的深入總結(jié)。但是的數(shù)據(jù)流是完全不同的東西。數(shù)據(jù)流是單體,并且在函數(shù)式編程中起到重要作用。列表上的所有流式操作請見數(shù)據(jù)流的?;镜臄?shù)據(jù)流使用特殊的表達(dá)式,例如,而不是,而不是。 Java 8 數(shù)據(jù)流教程 原文:Java 8 Stream Tutorial 譯者:飛龍 協(xié)議:CC BY-NC-SA 4.0 這個示例驅(qū)動的教程是J...
摘要:內(nèi)部迭代與使用迭代器顯式迭代的集合不同,流的迭代操作是在背后進(jìn)行的。流只能遍歷一次請注意,和迭代器類似,流只能遍歷一次。 流(Stream) 流是什么 流是Java API的新成員,它允許你以聲明性方式處理數(shù)據(jù)集合(通過查詢語句來表達(dá),而不是臨時(shí)編寫一個實(shí)現(xiàn))。就現(xiàn)在來說,你可以把它們看成遍歷數(shù)據(jù)集的高級迭代器。此外,流還可以透明地并行處理,你無需寫任何多線程代碼了!我會在后面的筆記中...
摘要:元素序列流也提供了一個接口,可以訪問特定元素類型的一組有序值。因?yàn)榧鲜菙?shù)據(jù)結(jié)構(gòu),所以它的主要目的是以特定的時(shí)間空間復(fù)雜度存儲和訪問元素如與。請注意,從有序集合生成流時(shí)會保留原有的順序。由列表生成的流,其元素順序與列表一致。 流是什么 流是Java API的新成員,它允許你以聲明性方式處理數(shù)據(jù)集合(通過查詢語句來表達(dá),而不是臨時(shí)編寫一個實(shí)現(xiàn))??梢园阉鼈兛闯杀闅v數(shù)據(jù)集的高級迭代器。此外...
摘要:需要注意的是很多流操作本身就會返回一個流,所以多個操作可以直接連接起來,如下圖這樣,操作可以進(jìn)行鏈?zhǔn)秸{(diào)用,并且并行流還可以實(shí)現(xiàn)數(shù)據(jù)流并行處理操作。為集合創(chuàng)建并行流。 上一篇文章,小樂給大家介紹了《Java8新特性之方法引用》,下面接下來小樂將會給大家介紹Java8新特性之Stream,稱之為流,本篇文章為上半部分。 1、什么是流? Java Se中對于流的操作有輸入輸出IO流,而Jav...
摘要:大家好,我是樂字節(jié)的小樂。需要注意的是很多流操作本身就會返回一個流,所以多個操作可以直接連接起來,如下圖這樣,操作可以進(jìn)行鏈?zhǔn)秸{(diào)用,并且并行流還可以實(shí)現(xiàn)數(shù)據(jù)流并行處理操作。為集合創(chuàng)建并行流。 大家好,我是樂字節(jié)的小樂。說起流,我們會聯(lián)想到手機(jī)、電腦組裝流水線,物流倉庫商品包裝流水線等等,如果把手機(jī) ,電腦,包裹看做最終結(jié)果的話,那么加工商品前的各種零部件就可以看做數(shù)據(jù)源,而中間一系列的...
閱讀 4147·2021-11-18 13:19
閱讀 1197·2021-10-11 10:58
閱讀 3305·2019-08-29 16:39
閱讀 3164·2019-08-26 12:08
閱讀 2068·2019-08-26 11:33
閱讀 2472·2019-08-23 18:30
閱讀 1338·2019-08-23 18:21
閱讀 2545·2019-08-23 18:18