java8 stream案例分析
生活随笔
收集整理的這篇文章主要介紹了
java8 stream案例分析
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
java8 stream
- Stream是java8 推出的一個處理集合類的一個全新的接口,在工作當中經常用到,并且他的預發規則與我們平臺的有一點不一樣,是流式的處理,非常類似RXJava的一個風格。
- java中對Stream的定義是:
-
以上的的語義包含兩部分:
- Stream是元素的集合,這點讓Stream看起來有一些類似Iterator
- 可以支持順序和并行的對原Stream進行匯聚的操作
-
剛學習Stream時候可以當一個高級的Iterator,原本的Iterator,用戶只能逐個遍歷每個元素,但是Stream用戶只需要給出對其包含元素執行什么操作,也就是通過給Stream傳遞某一個的操作符或者方法,他會將集合中所有元素使用你給定的方法或者操作符進行修改。
-
以下總結是我工作中用到的一些,會給出具體案例,初衷只是為了給自己一個參考,因為經常是在使用的時候,會忘記他的語法規則,或者忘記他的一些參數,以此作為一個記錄。
-
以下用到的基礎對象:
Stream 流操作
/*** Stream 流操作** 類似Rxjava中的流操作* */public static void streamBuildList(){//stream 快速成成listList<Integer> ofList = Stream.of(1,2,3,4,5).collect(Collectors.toList());//安指定規律生成流List<Integer> iteraterList = Stream.iterate(1, (x) -> x+2).limit(100).collect(Collectors.toList());//生成隨機數流List<Double> generateList = Stream.generate(Math::random).limit(199).collect(Collectors.toList());}Stream 流元素操作
/*** Stream 流中間操作* distinct 更具hashCode,equals 反復去重* filter過濾* skip 跳過n個元素* limit獲取n個元素* */public static void streamTest(){//生成隨機數流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表達式映射
/*** Stream map表達式映射* */public static void testStreamMap(List<FmResult> list){//傳遞一個函數給map,他會映射到每一個元素上Set<String> resultlist = list.stream().map(result -> result.getPlatform().replace(",", "")).collect(Collectors.toSet());//復雜表達式處理List<FmResult> fmResults = list.stream().map( result -> {result.setPlatform(result.getPlatform().substring(0,1));return result;}).collect(Collectors.toList());}Stream peek消費元素
/*** Stream peek消費元素* peek 和map操作一樣,當peek接受的是一個Consumer 表達式沒有返回值,map接受的是Function表達式有返回值* */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* 一對多,將一個元素拆分成多個元素,流元素變多,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:接收一個 Predicate 函數,當流中每個元素都符合該斷言時才返回true,否則返回false* noneMatch:接收一個 Predicate 函數,當流中每個元素都不符合該斷言時才返回true,否則返回false* anyMatch:接收一個 Predicate 函數,只要流中有一個元素滿足該斷言則返回true,否則返回false* findFirst:返回流中第一個元素* findAny:返回流中的任意元素* count:返回流中元素的總個數* 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 自己已經實現了Compareable接口List<String> strList = Arrays.asList("a2","a1","b4","c1","d5","a6");strList.stream().sorted().forEach(System.out::print);System.out.println();//自實現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 表達式list 轉 map
/*** Stream 表達式list -->map* (key1, key2) -> key1 作用在于如果存在相同id的數據,取第一個* */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 表達式 list --> map groupingBy分組* */public static void streamGroupingBy(List<FmResult> list){Map<String, List<FmResult>> fmMap = list.stream().collect(Collectors.groupingBy(FmResult::getPlatform));//按排平臺分組,并返回數量Map<String, Long> fmCountMap = list.stream().collect(Collectors.groupingBy(FmResult::getPlatform, Collectors.counting()));}Stream partitioningBy分區
/*** Stream partitioningBy分區* 按排序值 > 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 規約 reducing
/*** Stream 規約 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() : 計算平均數
/*** stream Collectors.averagingDouble()、Collectors.averagingInt()、Collectors.averagingLong() : 計算平均數* */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遇到了在補充
總結
以上是生活随笔為你收集整理的java8 stream案例分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 桂龙药膏怎么样
- 下一篇: 数据结构与算法--数字在排序数组中出现次