java8-Stream集合操作快速上手

目錄

  • Stream簡介
  • 為什么要使用Stream
  • 實(shí)例數(shù)據(jù)源
  • Filter
  • Map
  • FlatMap
  • Reduce
  • Collect
  • Optional
  • 并發(fā)
  • 調(diào)試

Stream簡介

  • Java 8引入了全新的Stream API剿干。這里的Stream和I/O流不同,它更像具有Iterable的集合類迂烁,但行為和集合類又有所不同。
  • stream是對(duì)集合對(duì)象功能的增強(qiáng)寨蹋,它專注于對(duì)集合對(duì)象進(jìn)行各種非常便利、高效的聚合操作,或者大批量數(shù)據(jù)操作臭增。
  • 只要給出需要對(duì)其包含的元素執(zhí)行什么操作横辆,比如 “過濾掉長度大于 10 的字符串”撇他、“獲取每個(gè)字符串的首字母”等,Stream 會(huì)隱式地在內(nèi)部進(jìn)行遍歷狈蚤,做出相應(yīng)的數(shù)據(jù)轉(zhuǎn)換困肩。

為什么要使用Stream

  • 函數(shù)式編程帶來的好處尤為明顯。這種代碼更多地表達(dá)了業(yè)務(wù)邏輯的意圖脆侮,而不是它的實(shí)現(xiàn)機(jī)制锌畸。易讀的代碼也易于維護(hù)、更可靠靖避、更不容易出錯(cuò)潭枣。
  • 高端

實(shí)例數(shù)據(jù)源

public class Data {
    private static List<PersonModel> list = null;

    static {
        PersonModel wu = new PersonModel("wu qi", 18, "男");
        PersonModel zhang = new PersonModel("zhang san", 19, "男");
        PersonModel wang = new PersonModel("wang si", 20, "女");
        PersonModel zhao = new PersonModel("zhao wu", 20, "男");
        PersonModel chen = new PersonModel("chen liu", 21, "男");
        list = Arrays.asList(wu, zhang, wang, zhao, chen);
    }

    public static List<PersonModel> getData() {
        return list;
    }
} 

Filter

  • 遍歷數(shù)據(jù)并檢查其中的元素時(shí)使用比默。
  • filter接受一個(gè)函數(shù)作為參數(shù),該函數(shù)用Lambda表達(dá)式表示卸耘。
image.png
    /**
     * 過濾所有的男性
     */
    public static void fiterSex(){
        List<PersonModel> data = Data.getData();

        //old
        List<PersonModel> temp=new ArrayList<>();
        for (PersonModel person:data) {
            if ("男".equals(person.getSex())){
                temp.add(person);
            }
        }
        System.out.println(temp);
        //new
        List<PersonModel> collect = data
                .stream()
                .filter(person -> "男".equals(person.getSex()))
                .collect(toList());
        System.out.println(collect);
    }

    /**
     * 過濾所有的男性 并且小于20歲
     */
    public static void fiterSexAndAge(){
        List<PersonModel> data = Data.getData();

        //old
        List<PersonModel> temp=new ArrayList<>();
        for (PersonModel person:data) {
            if ("男".equals(person.getSex())&&person.getAge()<20){
                temp.add(person);
            }
        }

        //new 1
        List<PersonModel> collect = data
                .stream()
                .filter(person -> {
                    if ("男".equals(person.getSex())&&person.getAge()<20){
                        return true;
                    }
                    return false;
                })
                .collect(toList());
        //new 2
        List<PersonModel> collect1 = data
                .stream()
                .filter(person -> ("男".equals(person.getSex())&&person.getAge()<20))
                .collect(toList());

    }

Map

  • map生成的是個(gè)一對(duì)一映射,for的作用
  • 比較常用
  • 而且很簡單
image.png
   /**
     * 取出所有的用戶名字
     */
    public static void getUserNameList(){
        List<PersonModel> data = Data.getData();

        //old
        List<String> list=new ArrayList<>();
        for (PersonModel persion:data) {
            list.add(persion.getName());
        }
        System.out.println(list);

        //new 1
        List<String> collect = data.stream().map(person -> person.getName()).collect(toList());
        System.out.println(collect);

        //new 2
        List<String> collect1 = data.stream().map(PersonModel::getName).collect(toList());
        System.out.println(collect1);

        //new 3
        List<String> collect2 = data.stream().map(person -> {
            System.out.println(person.getName());
            return person.getName();
        }).collect(toList());
    }

FlatMap

  • 顧名思義退敦,跟map差不多,更深層次的操作

  • 但還是有區(qū)別的

  • map和flat返回值不同

  • Map 每個(gè)輸入元素,都按照規(guī)則轉(zhuǎn)換成為另外一個(gè)元素蚣抗。
    還有一些場景侈百,是一對(duì)多映射關(guān)系的,這時(shí)需要 flatMap翰铡。

  • Map一對(duì)一

  • Flatmap一對(duì)多

  • map和flatMap的方法聲明是不一樣的

    • <r> Stream<r> map(Function mapper);
    • <r> Stream<r> flatMap(Function> mapper);
  • map和flatMap的區(qū)別:我個(gè)人認(rèn)為钝域,flatMap的可以處理更深層次的數(shù)據(jù),入?yún)槎鄠€(gè)list锭魔,結(jié)果可以返回為一個(gè)list例证,而map是一對(duì)一的,入?yún)⑹嵌鄠€(gè)list迷捧,結(jié)果返回必須是多個(gè)list织咧。通俗的說,如果入?yún)⒍际菍?duì)象漠秋,那么flatMap可以操作對(duì)象里面的對(duì)象笙蒙,而map只能操作第一層。

image.png
public static void flatMapString() {
        List<PersonModel> data = Data.getData();
        //返回類型不一樣
        List<String> collect = data.stream()
                .flatMap(person -> Arrays.stream(person.getName().split(" "))).collect(toList());

        List<Stream<String>> collect1 = data.stream()
                .map(person -> Arrays.stream(person.getName().split(" "))).collect(toList());

        //用map實(shí)現(xiàn)
        List<String> collect2 = data.stream()
                .map(person -> person.getName().split(" "))
                .flatMap(Arrays::stream).collect(toList());
        //另一種方式
        List<String> collect3 = data.stream()
                .map(person -> person.getName().split(" "))
                .flatMap(str -> Arrays.asList(str).stream()).collect(toList());
    }

Reduce

  • 感覺類似遞歸
  • 數(shù)字(字符串)累加
  • 個(gè)人沒咋用過
image.png
 public static void reduceTest(){
        //累加庆锦,初始化值是 10
        Integer reduce = Stream.of(1, 2, 3, 4)
                .reduce(10, (count, item) ->{
            System.out.println("count:"+count);
            System.out.println("item:"+item);
            return count + item;
        } );
        System.out.println(reduce);

        Integer reduce1 = Stream.of(1, 2, 3, 4)
                .reduce(0, (x, y) -> x + y);
        System.out.println(reduce1);

        String reduce2 = Stream.of("1", "2", "3")
                .reduce("0", (x, y) -> (x + "," + y));
        System.out.println(reduce2);
    }

Collect

  • collect在流中生成列表捅位,map,等常用的數(shù)據(jù)結(jié)構(gòu)
  • toList()
  • toSet()
  • toMap()
  • 自定義
 /**
     * toList
     */
    public static void toListTest(){
        List<PersonModel> data = Data.getData();
        List<String> collect = data.stream()
                .map(PersonModel::getName)
                .collect(Collectors.toList());
    }

    /**
     * toSet
     */
    public static void toSetTest(){
        List<PersonModel> data = Data.getData();
        Set<String> collect = data.stream()
                .map(PersonModel::getName)
                .collect(Collectors.toSet());
    }

    /**
     * toMap
     */
    public static void toMapTest(){
        List<PersonModel> data = Data.getData();
        Map<String, Integer> collect = data.stream()
                .collect(
                        Collectors.toMap(PersonModel::getName, PersonModel::getAge)
                );

        data.stream()
                .collect(Collectors.toMap(per->per.getName(), value->{
            return value+"1";
        }));
    }

    /**
     * 指定類型
     */
    public static void toTreeSetTest(){
        List<PersonModel> data = Data.getData();
        TreeSet<PersonModel> collect = data.stream()
                .collect(Collectors.toCollection(TreeSet::new));
        System.out.println(collect);
    }

    /**
     * 分組
     */
    public static void toGroupTest(){
        List<PersonModel> data = Data.getData();
        Map<Boolean, List<PersonModel>> collect = data.stream()
                .collect(Collectors.groupingBy(per -> "男".equals(per.getSex())));
        System.out.println(collect);
    }

    /**
     * 分隔
     */
    public static void toJoiningTest(){
        List<PersonModel> data = Data.getData();
        String collect = data.stream()
                .map(personModel -> personModel.getName())
                .collect(Collectors.joining(",", "{", "}"));
        System.out.println(collect);
    }

    /**
     * 自定義
     */
    public static void reduce(){
        List<String> collect = Stream.of("1", "2", "3").collect(
                Collectors.reducing(new ArrayList<String>(), x -> Arrays.asList(x), (y, z) -> {
                    y.addAll(z);
                    return y;
                }));
        System.out.println(collect);
    }

Optional

  • Optional 是為核心類庫新設(shè)計(jì)的一個(gè)數(shù)據(jù)類型搂抒,用來替換 null 值艇搀。
  • 人們對(duì)原有的 null 值有很多抱怨,甚至連發(fā)明這一概念的Tony Hoare也是如此求晶,他曾說這是自己的一個(gè)“價(jià)值連城的錯(cuò)誤”
  • 用處很廣焰雕,不光在lambda中,哪都能用
  • Optional.of(T)芳杏,T為非空淀散,否則初始化報(bào)錯(cuò)
  • Optional.ofNullable(T),T為任意蚜锨,可以為空
  • isPresent(),相當(dāng)于 慢蜓!=null
  • ifPresent(T)亚再, T可以是一段lambda表達(dá)式 ,或者其他代碼晨抡,非空則執(zhí)行
public static void main(String[] args) {


        PersonModel personModel=new PersonModel();

        //對(duì)象為空則打出 -
        Optional<Object> o = Optional.of(personModel);
        System.out.println(o.isPresent()?o.get():"-");

        //名稱為空則打出 -
        Optional<String> name = Optional.ofNullable(personModel.getName());
        System.out.println(name.isPresent()?name.get():"-");

        //如果不為空氛悬,則打出xxx
        Optional.ofNullable("test").ifPresent(na->{
            System.out.println(na+"ifPresent");
        });

        //如果空则剃,則返回指定字符串
        System.out.println(Optional.ofNullable(null).orElse("-"));
        System.out.println(Optional.ofNullable("1").orElse("-"));

        //如果空,則返回 指定方法如捅,或者代碼
        System.out.println(Optional.ofNullable(null).orElseGet(()->{
            return "hahah";
        }));
        System.out.println(Optional.ofNullable("1").orElseGet(()->{
            return "hahah";
        }));

        //如果空棍现,則可以拋出異常
        System.out.println(Optional.ofNullable("1").orElseThrow(()->{
            throw new RuntimeException("ss");
        }));


//        Objects.requireNonNull(null,"is null");


        //利用 Optional 進(jìn)行多級(jí)判斷
        EarthModel earthModel1 = new EarthModel();
        //old
        if (earthModel1!=null){
            if (earthModel1.getTea()!=null){
                //...
            }
        }
        //new
        Optional.ofNullable(earthModel1)
                .map(EarthModel::getTea)
                .map(TeaModel::getType)
                .isPresent();


//        Optional<EarthModel> earthModel = Optional.ofNullable(new EarthModel());
//        Optional<List<PersonModel>> personModels = earthModel.map(EarthModel::getPersonModels);
//        Optional<Stream<String>> stringStream = personModels.map(per -> per.stream().map(PersonModel::getName));


        //判斷對(duì)象中的list
        Optional.ofNullable(new EarthModel())
                .map(EarthModel::getPersonModels)
                .map(pers->pers
                        .stream()
                        .map(PersonModel::getName)
                        .collect(toList()))
                .ifPresent(per-> System.out.println(per));


        List<PersonModel> models=Data.getData();
        Optional.ofNullable(models)
                .map(per -> per
                        .stream()
                        .map(PersonModel::getName)
                        .collect(toList()))
                .ifPresent(per-> System.out.println(per));

    }

并發(fā)

  • stream替換成parallelStream或 parallel

  • 輸入流的大小并不是決定并行化是否會(huì)帶來速度提升的唯一因素,性能還會(huì)受到編寫代碼的方式和核的數(shù)量的影響

  • 影響性能的五要素是:數(shù)據(jù)大小镜遣、源數(shù)據(jù)結(jié)構(gòu)己肮、值是否裝箱、可用的CPU核數(shù)量悲关,以及處理每個(gè)元素所花的時(shí)間

 //根據(jù)數(shù)字的大小谎僻,有不同的結(jié)果
    private static int size=10000000;
    public static void main(String[] args) {
        System.out.println("-----------List-----------");
        testList();
        System.out.println("-----------Set-----------");
        testSet();
    }

    /**
     * 測試list
     */
    public static void testList(){
        List<Integer> list = new ArrayList<>(size);
        for (Integer i = 0; i < size; i++) {
            list.add(new Integer(i));
        }

        List<Integer> temp1 = new ArrayList<>(size);
        //老的
        long start=System.currentTimeMillis();
        for (Integer i: list) {
            temp1.add(i);
        }
        System.out.println(+System.currentTimeMillis()-start);

        //同步
        long start1=System.currentTimeMillis();
        list.stream().collect(Collectors.toList());
        System.out.println(System.currentTimeMillis()-start1);

        //并發(fā)
        long start2=System.currentTimeMillis();
        list.parallelStream().collect(Collectors.toList());
        System.out.println(System.currentTimeMillis()-start2);
    }

    /**
     * 測試set
     */
    public static void testSet(){
        List<Integer> list = new ArrayList<>(size);
        for (Integer i = 0; i < size; i++) {
            list.add(new Integer(i));
        }

        Set<Integer> temp1 = new HashSet<>(size);
        //老的
        long start=System.currentTimeMillis();
        for (Integer i: list) {
            temp1.add(i);
        }
        System.out.println(+System.currentTimeMillis()-start);

        //同步
        long start1=System.currentTimeMillis();
        list.stream().collect(Collectors.toSet());
        System.out.println(System.currentTimeMillis()-start1);

        //并發(fā)
        long start2=System.currentTimeMillis();
        list.parallelStream().collect(Collectors.toSet());
        System.out.println(System.currentTimeMillis()-start2);
    }

調(diào)試

  • list.map.fiter.map.xx 為鏈?zhǔn)秸{(diào)用,最終調(diào)用collect(xx)返回結(jié)果

  • 分惰性求值和及早求值

  • 判斷一個(gè)操作是惰性求值還是及早求值很簡單:只需看它的返回值寓辱。如果返回值是 Stream艘绍,那么是惰性求值;如果返回值是另一個(gè)值或?yàn)榭眨敲淳褪羌霸缜笾碉ぁJ褂眠@些操作的理想方式就是形成一個(gè)惰性求值的鏈诱鞠,最后用一個(gè)及早求值的操作返回想要的結(jié)果。

  • 通過peek可以查看每個(gè)值这敬,同時(shí)能繼續(xù)操作流

private static void peekTest() {
        List<PersonModel> data = Data.getData();

        //peek打印出遍歷的每個(gè)per
        data.stream().map(per->per.getName()).peek(p->{
            System.out.println(p);
        }).collect(toList());
    }

請(qǐng)各路大佬指教

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末航夺,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子鹅颊,更是在濱河造成了極大的恐慌敷存,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,490評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件堪伍,死亡現(xiàn)場離奇詭異锚烦,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)帝雇,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門涮俄,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人尸闸,你說我怎么就攤上這事彻亲。” “怎么了吮廉?”我有些...
    開封第一講書人閱讀 165,830評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵苞尝,是天一觀的道長。 經(jīng)常有香客問我宦芦,道長宙址,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,957評(píng)論 1 295
  • 正文 為了忘掉前任调卑,我火速辦了婚禮抡砂,結(jié)果婚禮上大咱,老公的妹妹穿的比我還像新娘。我一直安慰自己注益,他們只是感情好碴巾,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評(píng)論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著丑搔,像睡著了一般厦瓢。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上低匙,一...
    開封第一講書人閱讀 51,754評(píng)論 1 307
  • 那天旷痕,我揣著相機(jī)與錄音,去河邊找鬼顽冶。 笑死欺抗,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的强重。 我是一名探鬼主播绞呈,決...
    沈念sama閱讀 40,464評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼间景!你這毒婦竟也來了佃声?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤倘要,失蹤者是張志新(化名)和其女友劉穎圾亏,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體封拧,經(jīng)...
    沈念sama閱讀 45,847評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡志鹃,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評(píng)論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了泽西。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片曹铃。...
    茶點(diǎn)故事閱讀 40,137評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖捧杉,靈堂內(nèi)的尸體忽然破棺而出陕见,到底是詐尸還是另有隱情,我是刑警寧澤味抖,帶...
    沈念sama閱讀 35,819評(píng)論 5 346
  • 正文 年R本政府宣布评甜,位于F島的核電站,受9級(jí)特大地震影響仔涩,放射性物質(zhì)發(fā)生泄漏忍坷。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望承匣。 院中可真熱鬧,春花似錦锤悄、人聲如沸韧骗。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽袍暴。三九已至,卻和暖如春隶症,著一層夾襖步出監(jiān)牢的瞬間政模,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評(píng)論 1 272
  • 我被黑心中介騙來泰國打工蚂会, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留淋样,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,409評(píng)論 3 373
  • 正文 我出身青樓胁住,卻偏偏與公主長得像趁猴,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子彪见,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • Jav8中儡司,在核心類庫中引入了新的概念,流(Stream)余指。流使得程序媛們得以站在更高的抽象層次上對(duì)集合進(jìn)行操作捕犬。...
    仁昌居士閱讀 3,638評(píng)論 0 6
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)酵镜,斷路器碉碉,智...
    卡卡羅2017閱讀 134,672評(píng)論 18 139
  • 了解Stream ? Java8中有兩個(gè)最為重要的改變,一個(gè)是Lambda表達(dá)式笋婿,另一個(gè)就是Stream AP...
    龍歷旗閱讀 3,324評(píng)論 3 4
  • Java8 in action 沒有共享的可變數(shù)據(jù)誉裆,將方法和函數(shù)即代碼傳遞給其他方法的能力就是我們平常所說的函數(shù)式...
    鐵牛很鐵閱讀 1,233評(píng)論 1 2
  • Int Double Long 設(shè)置特定的stream類型, 提高性能缸濒,增加特定的函數(shù) 無存儲(chǔ)足丢。stream不是一...
    patrick002閱讀 1,274評(píng)論 0 0