Stream和lambda的常用api(下)

流的操作類型

1,中間操作

一個流可以後面跟隨0個或者多箇中間操作.其主要目的是打開流,作出某種程度的數據映射/過濾,然後返回一個新的流,交給下一個操作使用.這類操作都是惰性化的,僅僅調用這類方法,並沒有真正開始流的遍歷,真正的遍歷需等到終端操作時,常見的中間操作有filter,map等

2,終端操作

一個流有且只能有一個終端操作,當這個操作執行後,流就被關閉了,無法再被操作.因此一個 流只能被遍歷一次,若想再遍歷需要通過源數據再生成新的流.終端操作的執行,纔會真正開始流的遍歷.count,collect等都屬於終端遍歷.

流使用

中間操作

filter篩選

        List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
        List<Integer> collect = integerList.stream().filter(i -> i > 3).collect(Collectors.toList());
        for (Integer integer : collect) {
            System.out.println(integer);
        }

過濾得到大於3的值

distinct去重

List<Integer> integers = Arrays.asList(1, 1, 2, 2,3,3, 4, 5);
        List<Integer> collect = integers.stream().distinct().collect(Collectors.toList());

去除重複的2,3數據

limit返回指定流個數

List<Integer> integers = Arrays.asList(1, 1, 2, 2,3,3, 4, 5);
List<Integer> collect = integers.stream().limit(110).collect(Collectors.toList());
System.out.println(collect.size());

此操作多與排序進行操作,進行一系列操作後,進行取前幾個數字的組合;

如果limit的個數多於數組中的數字,則取當前數組的所有數據;

skip跳過流中的元素

        List<Integer> integers = Arrays.asList(1, 1, 2, 2,3,3, 4, 5);
        List<Integer> collect = integers.stream().skip(3).collect(Collectors.toList());
        System.out.println(collect.size());

skip是跳過流中的前幾個元素.skip的參數是參數的個數.

map流映射

所謂流映射就是將接受的元素映射成另外一個元素.

        List<String> integers = Arrays.asList("hello", "worldworld", "java");
        List<Integer> collect = integers.stream().map(String::length).collect(Collectors.toList());
        for (Integer integer : collect) {
            System.out.println(integer);
        }

元素匹配

提供了三種匹配方式

1,allMatch匹配所有.每個元素都要滿足

        List<String> integers = Arrays.asList("hello", "worldworld", "javao");
        if (integers.stream().allMatch(x->x.contains("o"))){
            System.out.println("該integers中都存在一個o值");
        }

2,anyMatch匹配任意...類似於contains

        List<String> integers = Arrays.asList("hello", "worldworld", "java");
        if (integers.stream().anyMatch(x->x.equals("java"))){
            System.out.println("該integers中存在一個java值");
        }

3,noneMatch全部不匹配

終端操作

count統計元素中流的個數

查找

查找第一個findFirst

        List<Integer> numbers = Arrays.asList(8,1,2,3,4,5,4,3,2,1,1);
        //返回的是第一個大於3的數值
        Optional<Integer> first = numbers.stream().filter(x -> x > 3).findFirst();
        System.out.println(first.get());

隨機查找一個findAny

   List<Integer> numbers = Arrays.asList(8,1,2,3,4,5,4,3,2,1,1);
        //返回的是第一個大於3的數值
        Optional<Integer> first = numbers.stream().filter(x -> x > 3).findAny();
        System.out.println(first.get());

求和

reduce將流中的元素組合起來

        List<Integer> numbers = Arrays.asList(8,1,2,3,4,5,4,3,2,1,1);
        //返回的是第一個大於3的數值
        Optional<Integer> first = numbers.stream().filter(x -> x > 3).findAny();
        Optional<Integer> sum = numbers.stream().reduce(Integer::sum);
        //求和
        int total = menu.stream().collect(summingInt(Dish::getCalories));
        int total1 = menu.stream().map(Dish::getCalories).reduce(0, Integer::sum);
        int total2 = menu.stream().mapToInt(Dish::getCalories).sum();
        int total3 = menu.stream().collect(summingInt(Dish::getCalories));

獲取流中最大最小值

        //獲取最大值等同
        Integer integer = menu.stream().map(Dish::getCalories).max(Integer::compareTo).get();
        int asInt = menu.stream().mapToInt(Dish::getCalories).max().getAsInt();

        Integer min2 = menu.stream().map(Dish::getCalories).collect(minBy(Integer::compareTo)).get();
        Integer min3 = menu.stream().map(Dish::getCalories).reduce(Integer::min).get();

推薦使用min、max、sum方法。因爲它最簡潔易讀,同時通過mapToInt將對象流轉換爲數值流,避免了裝箱和拆箱操作

求平均值

        //單獨求平均數
        double average = menu.stream().collect(averagingInt(Dish::getCalories));

        //求平均數,總和,最大數,最小數
        IntSummaryStatistics intSummaryStatistics = menu.stream().collect(summarizingInt(Dish::getCalories));
        double average1 = intSummaryStatistics.getAverage();
        int max = intSummaryStatistics.getMax();
        int min4 = intSummaryStatistics.getMin();
        long sum1 = intSummaryStatistics.getSum();

好多方法,幾乎你想要的,全都有....

for循環

        System.out.println("============================================");
        collect.forEach(System.out::println);
        collect.stream().forEach(System.out::println);
        System.out.println("============================================");

兩個結果集沒有發現不同,但是形式確實是不同...一個是Interator,一個是Stream的foreach方法;後者還是較快...(但是對於這個老生常談的比較...沒有什麼理論.自測也是不穩定的,看應用場景)

只取對象的一個元素進行集合

List<String> strings = menu.stream().map(Dish::getName).collect(toList());
Set<String> sets = menu.stream().map(Dish::getName).collect(toSet());

根據對象的某個屬性值進行拼接

String result = menu.stream().map(Dish::getName).collect(Collectors.joining(", "));

group分組

Map<Type, List<Dish>> result = dishList.stream().collect(groupingBy(Dish::getType));

group嵌套多層分組

Map<Type, List<Dish>> result = menu.stream().collect(groupingBy(Dish::getType,
        groupingBy(dish -> {
            if (dish.getCalories() <= 400) return CaloricLevel.DIET;
                else if (dish.getCalories() <= 700) return CaloricLevel.NORMAL;
                else return CaloricLevel.FAT;
        })));

partitioningBy分區

List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
Map<Boolean, List<Integer>> result = integerList.stream().collect(partitioningBy(i -> i < 3));

說實話,這篇文章是我抄的最認真的一次,但我感覺這也是我學的最認真的一次..因爲很多東西,如果只是看了一遍,後面又不記得了......這些api只是在後期的使用中,越用越熟,越用越順手...

 

摘自 https://mp.weixin.qq.com/s/x2BLSKiFakSD76FzFCBH7Q

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章