编程语言
首页 > 编程语言> > JavaStream流

JavaStream流

作者:互联网

案例

传统方法

package com.ding.stream;


import java.util.ArrayList;


public class MyStream1 {

    public static void main(String[] args) {
        ArrayList<String> list1 =new ArrayList<>();
        list1.add("张三丰");
        list1.add("张无极");
        list1.add("张翠山");
        list1.add("王二麻子");
        list1.add("张良");
        list1.add("谢广坤");

       //遍历list1把以张开头的元素添加到list2中
        ArrayList<String> list2 = new ArrayList<>();
        for (String s : list1) {
            if (s.startsWith("张")) {
                list2.add(s);
            }
        }

        //遍历list2,把长度为3的元素添加到list3中
        ArrayList<String> list3 = new ArrayList<>();
        for (String s : list2) {
            if (s.length() == 3) {

                list3.add(s);
            }
        }
        for (String s : list3) {
            System.out.println(s);
        }

        list3.forEach(
                (s) -> {System.out.println(s);}
        );

       
    }
}

Stream流

package com.ding.stream;


import java.util.ArrayList;


public class MyStream1 {

    public static void main(String[] args) {
        ArrayList<String> list1 =new ArrayList<>();
        list1.add("张三丰");
        list1.add("张无极");
        list1.add("张翠山");
        list1.add("王二麻子");
        list1.add("张良");
        list1.add("谢广坤");



        System.out.println("=======Stream流=======");
        list1.stream().filter(s->s.startsWith("张"))
                .filter(s->s.length() == 3)
                .forEach(s-> System.out.println(s));

       /* list1.stream().filter(s -> s.startsWith("张"))
                .filter(s -> s.length() == 3)
                .forEach(System.out::println);
*/
    }
}
/*=======Stream流=======
张三丰
张无极
张翠山
*/

标签:JavaStream,list1,list3,list2,add,ArrayList,out
来源: https://www.cnblogs.com/dss-99/p/15431357.html