玩轉(zhuǎn)Java8中的 Stream 之從零認(rèn)識(shí) Stream

作者:litesky

來(lái)源: http://m.itdecent.cn/p/11c925cdba50

相信Java8的Stream 大家都已聽(tīng)說(shuō)過(guò)了,但是可能大家不會(huì)用或者用的不熟,文章將帶大家從零開(kāi)始使用,循序漸進(jìn),帶你走向Stream的巔峰。

操作符

什么是操作符呢?操作符就是對(duì)數(shù)據(jù)進(jìn)行的一種處理工作,一道加工程序;就好像工廠的工人對(duì)流水線上的產(chǎn)品進(jìn)行一道加工程序一樣。

Stream的操作符大體上分為兩種:中間操作符和終止操作符

中間操作符

對(duì)于數(shù)據(jù)流來(lái)說(shuō),中間操作符在執(zhí)行制定處理程序后,數(shù)據(jù)流依然可以傳遞給下一級(jí)的操作符。

中間操作符包含8種(排除了parallel,sequential,這兩個(gè)操作并不涉及到對(duì)數(shù)據(jù)流的加工操作):

map(mapToInt,mapToLong,mapToDouble) 轉(zhuǎn)換操作符,把比如A->B,這里默認(rèn)提供了轉(zhuǎn)int,long,double的操作符。
flatmap(flatmapToInt,flatmapToLong,flatmapToDouble) 拍平操作比如把 int[]{2,3,4} 拍平 變成 2,3,4 也就是從原來(lái)的一個(gè)數(shù)據(jù)變成了3個(gè)數(shù)據(jù),這里默認(rèn)提供了拍平成int,long,double的操作符。
limit 限流操作,比如數(shù)據(jù)流中有10個(gè) 我只要出前3個(gè)就可以使用。
distint 去重操作,對(duì)重復(fù)元素去重,底層使用了equals方法。
filter 過(guò)濾操作,把不想要的數(shù)據(jù)過(guò)濾。
peek 挑出操作,如果想對(duì)數(shù)據(jù)進(jìn)行某些操作,如:讀取、編輯修改等。
skip 跳過(guò)操作,跳過(guò)某些元素。
sorted(unordered) 排序操作,對(duì)元素排序,前提是實(shí)現(xiàn)Comparable接口,當(dāng)然也可以自定義比較器。

終止操作符

數(shù)據(jù)經(jīng)過(guò)中間加工操作,就輪到終止操作符上場(chǎng)了;終止操作符就是用來(lái)對(duì)數(shù)據(jù)進(jìn)行收集或者消費(fèi)的,數(shù)據(jù)到了終止操作這里就不會(huì)向下流動(dòng)了,終止操作符只能使用一次。

collect 收集操作,將所有數(shù)據(jù)收集起來(lái),這個(gè)操作非常重要,官方的提供的Collectors 提供了非常多收集器,可以說(shuō)Stream 的核心在于Collectors。
count 統(tǒng)計(jì)操作,統(tǒng)計(jì)最終的數(shù)據(jù)個(gè)數(shù)。
findFirst、findAny 查找操作,查找第一個(gè)、查找任何一個(gè) 返回的類型為Optional。
noneMatch、allMatch、anyMatch 匹配操作,數(shù)據(jù)流中是否存在符合條件的元素 返回值為bool 值。
min、max 最值操作,需要自定義比較器,返回?cái)?shù)據(jù)流中最大最小的值。
reduce 規(guī)約操作,將整個(gè)數(shù)據(jù)流的值規(guī)約為一個(gè)值,count、min、max底層就是使用reduce。
forEach、forEachOrdered 遍歷操作,這里就是對(duì)最終的數(shù)據(jù)進(jìn)行消費(fèi)了。
toArray 數(shù)組操作,將數(shù)據(jù)流的元素轉(zhuǎn)換成數(shù)組。
這里只介紹了Stream,并沒(méi)有涉及到IntStream、LongStream、DoubleStream,這三個(gè)流實(shí)現(xiàn)了一些特有的操作符,我將在后續(xù)文章中介紹到。Java知音公眾號(hào)內(nèi)回復(fù)“面試題聚合”,送你一份各大公司面試匯總寶典。

說(shuō)了這么多,只介紹這些操作符還遠(yuǎn)遠(yuǎn)不夠;俗話說(shuō),實(shí)踐出真知。那么,Let‘s go。

代碼演練

Stream 的一系列操作必須要使用終止操作,否者整個(gè)數(shù)據(jù)流是不會(huì)流動(dòng)起來(lái)的,即處理操作不會(huì)執(zhí)行。

map,可以看到 map 操作符要求輸入一個(gè)Function的函數(shù)是接口實(shí)例,功能是將T類型轉(zhuǎn)換成R類型的。

image

map操作將原來(lái)的單詞 轉(zhuǎn)換成了每個(gè)單的長(zhǎng)度,利用了String自身的length()方法,該方法返回類型為int。這里我直接使用了lambda表達(dá)式,關(guān)于lambda表達(dá)式 還請(qǐng)讀者們自行了解吧。

public class Main {

    public static void main(String[] args) {
        Stream.of("apple","banana","orange","waltermaleon","grape")
                .map(e->e.length()) //轉(zhuǎn)成單詞的長(zhǎng)度 int
                .forEach(e->System.out.println(e)); //輸出
    }
}

當(dāng)然也可以這樣,這里使用了成員函數(shù)引用,為了便于讀者們理解,后續(xù)的例子中將使用lambda表達(dá)式而非函數(shù)引用。

public class Main {

    public static void main(String[] args) {
         Stream.of("apple","banana","orange","waltermaleon","grape")
                .map(String::length) //轉(zhuǎn)成單詞的長(zhǎng)度 int
                .forEach(System.out::println);
    }
}

結(jié)果如圖:

image

mapToInt 將數(shù)據(jù)流中得元素轉(zhuǎn)成Int,這限定了轉(zhuǎn)換的類型Int,最終產(chǎn)生的流為IntStream,及結(jié)果只能轉(zhuǎn)化成int。

image
public class Main {

    public static void main(String[] args) {
         Stream.of("apple", "banana", "orange", "waltermaleon", "grape")
                .mapToInt(e -> e.length()) //轉(zhuǎn)成int
                .forEach(e -> System.out.println(e));
    }
}

mapToInt如圖:


image

mapToLong、mapToDouble 與mapToInt 類似

public class Main {

    public static void main(String[] args) {
         Stream.of("apple", "banana", "orange", "waltermaleon", "grape")
                .mapToLong(e -> e.length()) //轉(zhuǎn)成long ,本質(zhì)上是int 但是存在類型自動(dòng)轉(zhuǎn)換
                .forEach(e -> System.out.println(e));
    }
}

mapToLong 如圖:

image
public class Main {

    public static void main(String[] args) {
         Stream.of("apple", "banana", "orange", "waltermaleon", "grape")
                .mapToDouble(e -> e.length()) //轉(zhuǎn)成Double ,自動(dòng)類型轉(zhuǎn)換成Double
                .forEach(e -> System.out.println(e));
    }
}

mapToDouble如圖:

image

flatmap 作用就是將元素拍平拍扁 ,將拍扁的元素重新組成Stream,并將這些Stream 串行合并成一條Stream

image
public class Main {

    public static void main(String[] args) {
        Stream.of("a-b-c-d","e-f-i-g-h")
                .flatMap(e->Stream.of(e.split("-")))
                .forEach(e->System.out.println(e));

    }
}

flatmap 如圖:

image

flatmapToInt、flatmapToLong、flatmapToDouble 跟flatMap 都類似的,只是類型被限定了,這里就不在舉例子了。

limit 限制元素的個(gè)數(shù),只需傳入 long 類型 表示限制的最大數(shù)

public class Main {

    public static void main(String[] args) {
        Stream.of(1,2,3,4,5,6)
                .limit(3) //限制三個(gè)
                .forEach(e->System.out.println(e)); //將輸出 前三個(gè) 1,2,3
    }
}

limit如圖:

image
image
public class Main {

    public static void main(String[] args) {

        Stream.of(1,2,3,1,2,5,6,7,8,0,0,1,2,3,1)
                .distinct() //去重
                .forEach(e->System.out.println(e));

    }
}

distinct 如圖:

image

filter 對(duì)某些元素進(jìn)行過(guò)濾,不符合篩選條件的將無(wú)法進(jìn)入流的下游

public class Main {

    public static void main(String[] args) {
        Stream.of(1,2,3,1,2,5,6,7,8,0,0,1,2,3,1)
                .filter(e->e>=5) //過(guò)濾小于5的
                .forEach(e->System.out.println(e));
    }
}

filter 如圖:

image

peek 挑選 ,將元素挑選出來(lái),可以理解為提前消費(fèi)

public class Main {

    public static void main(String[] args) {

        User w = new User("w",10);
        User x = new User("x",11);
        User y = new User("y",12);

        Stream.of(w,x,y)
                .peek(e->{e.setName(e.getAge()+e.getName());}) //重新設(shè)置名字 變成 年齡+名字
                .forEach(e->System.out.println(e.toString()));

    }

    static class User {

        private String name;

        private int age;

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

}

peek 如圖:

image

skip 跳過(guò) 元素

public class Main {

    public static void main(String[] args) {
        Stream.of(1,2,3,4,5,6,7,8,9)
                .skip(4) //跳過(guò)前四個(gè)
                .forEach(e->System.out.println(e)); //輸出的結(jié)果應(yīng)該只有5,6,7,8,9
    }
}

skip 如圖:

image

sorted 排序 底層依賴Comparable 實(shí)現(xiàn),也可以提供自定義比較器
這里Integer 實(shí)現(xiàn)了比較器

public class Main {

    public static void main(String[] args) {
        Stream.of(2,1,3,6,4,9,6,8,0)
                .sorted()
                .forEach(e->System.out.println(e));
    }
}

sorted 默認(rèn)比較器如圖:

image

這里使用自定義比較,當(dāng)然User 可以實(shí)現(xiàn)Comparable 接口

public class Main {

    public static void main(String[] args) {

        User x = new User("x",11);
        User y = new User("y",12);
        User w = new User("w",10);

        Stream.of(w,x,y)
                .sorted((e1,e2)->e1.age>e2.age?1:e1.age==e2.age?0:-1)
                .forEach(e->System.out.println(e.toString()));

    }

    static class User {

        private String name;

        private int age;

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

}

如圖:

image

collect 收集,使用系統(tǒng)提供的收集器可以將最終的數(shù)據(jù)流收集到List,Set,Map等容器中。
這里我使用collect 將元素收集到一個(gè)set中

public class Main {

    public static void main(String[] args) {
        Stream.of("apple", "banana", "orange", "waltermaleon", "grape")
                .collect(Collectors.toSet()) //set 容器
                .forEach(e -> System.out.println(e));
    }
}

咦?,不是說(shuō)終止操作符只能使用一次嗎,為什么這里調(diào)用了forEach 呢?forEach不僅僅是是Stream 中得操作符還是各種集合中得一個(gè)語(yǔ)法糖,不信咋們?cè)囋?。Java知音公眾號(hào)內(nèi)回復(fù)“面試題聚合”,送你一份各大公司面試匯總寶典。

public class Main {

    public static void main(String[] args) {

        Set<String> stringSet = Stream.of("apple", "banana", "orange", "waltermaleon", "grape")
                .collect(Collectors.toSet()); //收集的結(jié)果就是set
        stringSet.forEach(e->System.out.println(e)); set的語(yǔ)法糖forEach
}

結(jié)果如圖:

image

count 統(tǒng)計(jì)數(shù)據(jù)流中的元素個(gè)數(shù),返回的是long 類型

public class Main {

    public static void main(String[] args) {

        long count = Stream.of("apple", "banana", "orange", "waltermaleon", "grape")
                .count();

        System.out.println(count);
    }
}

count 如圖:

image

findFirst 獲取流中的第一個(gè)元素
這里找到第一個(gè)元素 apple

public class FindFirst {

    public static void main(String[] args) {
        Optional<String> stringOptional = Stream.of("apple", "banana", "orange", "waltermaleon", "grape")
                .findFirst();
        stringOptional.ifPresent(e->System.out.println(e));
    }
}

findFirst 結(jié)果如圖:

image

findAny 獲取流中任意一個(gè)元素

public class FindAny {

    public static void main(String[] args) {
        Optional<String> stringOptional = Stream.of("apple", "banana", "orange", "waltermaleon", "grape")
                .parallel()
                .findAny(); //在并行流下每次返回的結(jié)果可能一樣也可能不一樣
        stringOptional.ifPresent(e->System.out.println(e));
    }
}

findAny 在并行流下 使用結(jié)果:

輸出了orange

image

輸出了banana

image

noneMatch 數(shù)據(jù)流中得沒(méi)有一個(gè)元素與條件匹配的
這里 的作用是是判斷數(shù)據(jù)流中 一個(gè)都沒(méi)有與aa 相等元素 ,但是流中存在 aa ,所以最終結(jié)果應(yīng)該是false

public class NoneMatch {

    public static void main(String[] args) {
        boolean result = Stream.of("aa","bb","cc","aa")
                .noneMatch(e->e.equals("aa"));
        System.out.println(result);
    }
}

noneMatch 如圖:

image

allMatch和anyMatch 一個(gè)是全匹配,一個(gè)是任意匹配 和noneMatch 類似,這里就不在舉例了。

min 最小的一個(gè),傳入比較器,也可能沒(méi)有(如果數(shù)據(jù)流為空)

public class Main {

    public static void main(String[] args) {

        Optional<Integer> integerOptional = Stream.of(0,9,8,4,5,6,-1)
                .min((e1,e2)->e1.compareTo(e2));

        integerOptional.ifPresent(e->System.out.println(e));

    }

min如圖:

image

max 元素中最大的,需要傳入比較器,也可能沒(méi)有(流為Empty時(shí))

public class Main {

    public static void main(String[] args) {

        Optional<Integer> integerOptional = Stream.of(0,9,8,4,5,6,-1)
                .max((e1,e2)->e1.compareTo(e2));

        integerOptional.ifPresent(e->System.out.println(e));

    }
}

max 如圖:

image

reduce 是一個(gè)規(guī)約操作,所有的元素歸約成一個(gè),比如對(duì)所有元素求和,乘啊等。
這里實(shí)現(xiàn)了一個(gè)加法,指定了初始化的值

public class Main {
    public static void main(String[] args) {

        int sum = Stream.of(0,9,8,4,5,6,-1)
              .reduce(0,(e1,e2)->e1+e2);
        System.out.println(sum);
    }
}

reduce 如圖:

image

forEach
forEach 其實(shí)前就已經(jīng)見(jiàn)過(guò)了,對(duì)每個(gè)數(shù)據(jù)遍歷迭代

forEachOrdered 適用用于并行流的情況下進(jìn)行迭代,能保證迭代的有序性
這里通過(guò)并行的方式輸出數(shù)字

public class ForEachOrdered {
    public static void main(String[] args) {
        Stream.of(0,2,6,5,4,9,8,-1)
                .parallel()
                .forEachOrdered(e->{
                    System.out.println(Thread.currentThread().getName()+": "+e);});
    }
}

forEachOrdered 如圖:

image

toArray 轉(zhuǎn)成數(shù)組,可以提供自定義數(shù)組生成器

public class ToArray {
    public static void main(String[] args) {
        Object[] objects=Stream.of(0,2,6,5,4,9,8,-1)
                .toArray();

        for (int i = 0; i < objects.length; i++) {
            System.out.println(objects[I]);
        }
    }
}

toArray 如圖:

image

總結(jié)

Java8 Stream就帶大家認(rèn)識(shí)到這里,如果你能跟著我的文章把每一個(gè)例子都敲一遍,相信都能掌握這些操作符的初步用法。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容