java8 stream案例分析
生活随笔
收集整理的這篇文章主要介紹了
java8 stream案例分析
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
java8 stream
- Stream是java8 推出的一個(gè)處理集合類的一個(gè)全新的接口,在工作當(dāng)中經(jīng)常用到,并且他的預(yù)發(fā)規(guī)則與我們平臺的有一點(diǎn)不一樣,是流式的處理,非常類似RXJava的一個(gè)風(fēng)格。
- java中對Stream的定義是:
-
以上的的語義包含兩部分:
- Stream是元素的集合,這點(diǎn)讓Stream看起來有一些類似Iterator
- 可以支持順序和并行的對原Stream進(jìn)行匯聚的操作
-
剛學(xué)習(xí)Stream時(shí)候可以當(dāng)一個(gè)高級的Iterator,原本的Iterator,用戶只能逐個(gè)遍歷每個(gè)元素,但是Stream用戶只需要給出對其包含元素執(zhí)行什么操作,也就是通過給Stream傳遞某一個(gè)的操作符或者方法,他會將集合中所有元素使用你給定的方法或者操作符進(jìn)行修改。
-
以下總結(jié)是我工作中用到的一些,會給出具體案例,初衷只是為了給自己一個(gè)參考,因?yàn)榻?jīng)常是在使用的時(shí)候,會忘記他的語法規(guī)則,或者忘記他的一些參數(shù),以此作為一個(gè)記錄。
-
以下用到的基礎(chǔ)對象:
Stream 流操作
/*** Stream 流操作** 類似Rxjava中的流操作* */public static void streamBuildList(){//stream 快速成成listList<Integer> ofList = Stream.of(1,2,3,4,5).collect(Collectors.toList());//安指定規(guī)律生成流List<Integer> iteraterList = Stream.iterate(1, (x) -> x+2).limit(100).collect(Collectors.toList());//生成隨機(jī)數(shù)流List<Double> generateList = Stream.generate(Math::random).limit(199).collect(Collectors.toList());}Stream 流元素操作
/*** Stream 流中間操作* distinct 更具h(yuǎn)ashCode,equals 反復(fù)去重* filter過濾* skip 跳過n個(gè)元素* limit獲取n個(gè)元素* */public static void streamTest(){//生成隨機(jī)數(shù)流List<Double> generateList = Stream.generate(Math::random).limit(199).collect(Collectors.toList());List<Double> myDubleLIst = generateList.stream().filter(d -> d > 0.5).distinct().skip(4).limit(20).collect(Collectors.toList());myDubleLIst.forEach(System.out::println);}Stream map表達(dá)式映射
/*** Stream map表達(dá)式映射* */public static void testStreamMap(List<FmResult> list){//傳遞一個(gè)函數(shù)給map,他會映射到每一個(gè)元素上Set<String> resultlist = list.stream().map(result -> result.getPlatform().replace(",", "")).collect(Collectors.toSet());//復(fù)雜表達(dá)式處理List<FmResult> fmResults = list.stream().map( result -> {result.setPlatform(result.getPlatform().substring(0,1));return result;}).collect(Collectors.toList());}Stream peek消費(fèi)元素
/*** Stream peek消費(fèi)元素* peek 和map操作一樣,當(dāng)peek接受的是一個(gè)Consumer 表達(dá)式?jīng)]有返回值,map接受的是Function表達(dá)式有返回值* */public static void testStreamPeek(){FmResult result1 = new FmResult(1,"aa");FmResult result2 = new FmResult(2,"bb");FmResult result3 = new FmResult(3,"aa");FmResult result4 = new FmResult(4,"dd");List<FmResult> fmResults = Arrays.asList(result1,result2, result3, result4);List<FmResult> newResults = fmResults.stream().peek(result -> result.setFmName("123123")).collect(Collectors.toList());for (FmResult newResult: newResults) {System.out.println(newResult.getSortNo() + ": "+ newResult.getPlatform() + ": "+ newResult.getFmName());}}Stream flatMapToInt,flatMapToDouble,flatMapToLong
/*** Stream flatMapToInt,flatMapToDouble,flatMapToLong* 一對多,將一個(gè)元素拆分成多個(gè)元素,流元素變多,map是一對一* */public static void testStreamFlagMap(){FmResult result1 = new FmResult(1,"aa");FmResult result2 = new FmResult(2,"bb");FmResult result3 = new FmResult(3,"aa");FmResult result4 = new FmResult(4,"dd");List<FmResult> fmResults = Arrays.asList(result1,result2, result3, result4);IntStream platformStream = fmResults.stream().map(FmResult::getPlatform).flatMapToInt(String::chars);int[] ints = platformStream.toArray();System.out.println(ints.length +" :"+ ints[0]);}Stream 流的終止操作
/*** Stream 流的終止* allMatch:接收一個(gè) Predicate 函數(shù),當(dāng)流中每個(gè)元素都符合該斷言時(shí)才返回true,否則返回false* noneMatch:接收一個(gè) Predicate 函數(shù),當(dāng)流中每個(gè)元素都不符合該斷言時(shí)才返回true,否則返回false* anyMatch:接收一個(gè) Predicate 函數(shù),只要流中有一個(gè)元素滿足該斷言則返回true,否則返回false* findFirst:返回流中第一個(gè)元素* findAny:返回流中的任意元素* count:返回流中元素的總個(gè)數(shù)* max:返回流中元素最大值* min:返回流中元素最小值* */public static void testStreamTermal(){List<String> strList = Arrays.asList("a2","a1","b4","c1","d5","a6");boolean allMatch = strList.stream().allMatch(str -> str.equals("a1"));boolean noneMatch = strList.stream().noneMatch(str -> str.equals("x"));boolean anyMatch = strList.stream().anyMatch(str -> str.equals("a1"));String findFirst = strList.stream().findFirst().get();String findAny = strList.stream().findAny().get();Long count = strList.stream().count();String max = strList.stream().max(String::compareTo).get();String min = strList.stream().min(String::compareTo).get();}Stream 排序處理
/*** Stream 排序處理* */public static void testStreamSort(){//String 自己已經(jīng)實(shí)現(xiàn)了Compareable接口List<String> strList = Arrays.asList("a2","a1","b4","c1","d5","a6");strList.stream().sorted().forEach(System.out::print);System.out.println();//自實(shí)現(xiàn)Compareable接口FmResult result1 = new FmResult(1,"aa");FmResult result2 = new FmResult(2,"bb");FmResult result3 = new FmResult(3,"aa");FmResult result4 = new FmResult(4,"dd");List<FmResult> fmResults = Arrays.asList(result1,result2, result3, result4);List<FmResult> sortResults = fmResults.stream().sorted((k1,k2)->{if(k1.getPlatform().equals(k2.getPlatform())){return k1.getSortNo()-k2.getSortNo();}else {return k1.getPlatform().compareTo(k2.getPlatform());}}).collect(Collectors.toList());for (FmResult sortResult : sortResults) {System.out.println(sortResult.getSortNo() + ": "+ sortResult.getPlatform());}}Stream 表達(dá)式list 轉(zhuǎn) map
/*** Stream 表達(dá)式list -->map* (key1, key2) -> key1 作用在于如果存在相同id的數(shù)據(jù),取第一個(gè)* */public static Map<Long, FmResult> streamListTOMap(List<FmResult> list){return list.stream().collect(Collectors.toMap(FmResult::getId, Function.identity(), (key1, key2) -> key1));}Stream groupingBy分組
/*** Stream 表達(dá)式 list --> map groupingBy分組* */public static void streamGroupingBy(List<FmResult> list){Map<String, List<FmResult>> fmMap = list.stream().collect(Collectors.groupingBy(FmResult::getPlatform));//按排平臺分組,并返回?cái)?shù)量Map<String, Long> fmCountMap = list.stream().collect(Collectors.groupingBy(FmResult::getPlatform, Collectors.counting()));}Stream partitioningBy分區(qū)
/*** Stream partitioningBy分區(qū)* 按排序值 > 2 分組* */public static Map<Boolean, List<FmResult>> streamPartitioningBy(List<FmResult> list){return list.stream().collect(Collectors.partitioningBy(x -> x.getSortNo() > 2));}Stream 連接 joining
/*** Stream 連接 joining* */public static void streamJoining(){FmResult result1 = new FmResult(1,"aa");FmResult result2 = new FmResult(2,"bb");FmResult result3 = new FmResult(3,"aa");FmResult result4 = new FmResult(4,"dd");List<FmResult> fmResults = Arrays.asList(result1,result2, result3, result4);String platform = fmResults.stream().map(result -> result.getPlatform()).collect(Collectors.joining(","));System.out.println(platform);}Stream 規(guī)約 reducing
/*** Stream 規(guī)約 reducing* */public static void streamReducing(){FmResult result1 = new FmResult(1,"aa");FmResult result2 = new FmResult(2,"bb");FmResult result3 = new FmResult(3,"aa");FmResult result4 = new FmResult(4,"dd");List<FmResult> fmResults = Arrays.asList(result1,result2, result3, result4);Optional<Integer> sumSortNo = fmResults.stream().map(result ->result.getSortNo()).collect(Collectors.reducing(Integer::sum));System.out.println(sumSortNo.get());}stream Collectors.averagingDouble()、Collectors.averagingInt()、Collectors.averagingLong() : 計(jì)算平均數(shù)
/*** stream Collectors.averagingDouble()、Collectors.averagingInt()、Collectors.averagingLong() : 計(jì)算平均數(shù)* */public static void streamAveraging(){FmResult result1 = new FmResult(1,"aa");FmResult result2 = new FmResult(2,"bb");FmResult result3 = new FmResult(3,"aa");FmResult result4 = new FmResult(4,"dd");List<FmResult> fmResults = Arrays.asList(result1,result2, result3, result4);Double avgSortNo = fmResults.stream().collect(Collectors.averagingInt(FmResult::getSortNo));}其他api遇到了在補(bǔ)充
總結(jié)
以上是生活随笔為你收集整理的java8 stream案例分析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 桂龙药膏怎么样
- 下一篇: 数据结构与算法--数字在排序数组中出现次