Java8中Stream的使用技巧

 

来源:https://www.jianshu.com/p/9fe8632d0bc2

简介:

1.stream是对集合对象功能的增强,用于对集合对象的各种操作,或者大批量数据操作

2.stream会根据要求,隐式的进行内部便利,然后做出相应的数据转换

优点:

函数式编程使得代码更好的表达业务逻辑的意图,代码易读性高,也更易于维护

相关操作:

Filter

1.遍历数据并检查元素使用

2.filter接受一个函数作为参数,函数使用lambda表达式表示

public static void filter01(){
        ArrayList<People> people = new ArrayList<>();
        //old
        for(People p:peopleList){
            if("男".equals(p.getSex())){
                people.add(p);
            }
        }

        //new
        List<People> collect=peopleList.stream()
                .filter(people1 -> "男".equals(people1.getSex()))
                .collect(Collectors.toList());

    }
public static void filter02(){
        ArrayList<People> people = new ArrayList<>();
        //old
        for(People p:peopleList){
            if("男".equals(p.getSex())&&p.getAge()>18){
                people.add(p);
            }
        }
        
        //new
        List<People> collect=peopleList.stream()
                .filter(people1 -> "男".equals(people1.getSex())&&people1.getAge()>18)
                .collect(Collectors.toList());
    }

Map

map生成的是一对一的映射,简单常用(转化用)

public static void filterMap(){
        ArrayList<String> strings = new ArrayList<>();
        
        //old
        for(People p:peopleList){
            strings.add(p.getName());
        }
        
        //new 1
        List<String> s1=peopleList.stream()
                .map(people -> {
                    return people.getName();
                })
                .collect(Collectors.toList());
        
        //new 2
        List<String> s2=peopleList.stream()
                .map(people -> people.getName())
                .collect(Collectors.toList());
        
        //new 3
        List<String> s3=peopleList.stream()
                .map(People::getName)
                .collect(Collectors.toList());
    }

FlatMap

跟map类似,可以做转换工作,但是比map有更深层次的操作,map为一对一映射,flatMap为一对多的映射关系。flatMap可以处理更深层次的结构,入参为多个list,返回一个list。如果入参是对象的话,那么map只能操作一层,而flatMap可以操作对象中的对象

示例如下

public static void flatMapTest(){

        List<String> collect = peopleList.stream()
                .flatMap(people -> Arrays.stream(people.getName().split(" "))).collect(Collectors.toList());

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

    }

Reduce

对数字(字符串)进行累加

public static void reduceTest(){
        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:"+reduce);


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


        String reduce2 = Stream.of("1", "2", "3", "4")
                .reduce("0", (x, y) ->
                        (x + "," + y));
        System.out.println("reduce2:"+reduce2);
    }
count:10
item:1
count:11
item:2
count:13
item:3
count:16
item:4
reduce:20
reduce1:10
reduce2:0,1,2,3,4

Collect

collect在流中生成列表,map等常用的数据结构,toList,toMap,toSet,自定义

public static void collectTest(List<People> list){
        //toList
        List<String> collect = list.stream().map(
                People::getName
        ).collect(Collectors.toList());
        System.out.println("collect:"+collect);
        //toSet
        Set<String> collect1 = list.stream().map(
                People::getName
        ).collect(Collectors.toSet());
        System.out.println("collect1:"+collect1);
        //toMap
        Map<String, Integer> collect2 = list.stream().collect(Collectors.toMap(
                People::getName, People::getAge
        ));
        System.out.println("collect2:"+collect2);
        Map<String, Integer> collect3 = list.stream().collect(Collectors.toMap(p -> p.getName(), value -> (value.getAge())));
        System.out.println("collect3:"+collect3);

        //指定类型
        TreeSet<People> collect4 = list.stream().collect(Collectors.toCollection(TreeSet::new));
        System.out.println("collect4:"+collect4);

        //分组
        Map<Boolean, List<People>> collect5 = list.stream().collect(Collectors.groupingBy(p -> "男".equals(p.getSex())));
        System.out.println("collect5:"+collect5);

        //分隔 ??
        String collect6 = list.stream().map(
                people -> people.getName()
        )
                .collect(
                        Collectors.joining(",", "{", "}")
                );
        System.out.println("collect6:"+collect6);

        //自定义
        List<String> collect7 = 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(collect7);
    }

Optional

为核心类库设计的一种新的数据类型,用于替换null,不光在lambda中可以使用,哪都可以用,Optional.of(T),T为非空,否则初始化报错,Optional.ofNullable(T),T为任意值,可以为空,isPresent(),相当于!=null,isPresent(T),T可以是lambda表达式,也可以其他代码,非空则执行

public static void optionalTest(){
        People people = new People();
        //对象为空打出-
        Optional<People> people1 = Optional.of(people);
        System.out.println(people1.isPresent()?people1.get():"-");

        //对象名为空打出-
        Optional<String> name = Optional.ofNullable(people.getName());
        System.out.println(name.isPresent()?name.get():"-");

        //如果不为空,打印
        Optional.ofNullable("test").ifPresent(a-> System.out.println(a+" isPresent"));

        //如果为空  则打印
        System.out.println(Optional.ofNullable("test").orElse("-"));
        System.out.println(Optional.ofNullable(null).orElse("-"));

        //如果为空  则执行方法
        System.out.println(Optional.ofNullable("test").orElseGet(()->{
            return "----";
        }));
        System.out.println(Optional.ofNullable(null).orElseGet(()->{
            return "-=----";
        }));


        //利用option进行多级判断
        //old
        People people2 = new People();
        if(people2!=null){
            if(people2.getChild()!=null){

            }
        }

        //new
        boolean present = Optional.ofNullable(people2)
                .map(People::getChild)
                .isPresent();

        //判断对象中的list
        Optional.ofNullable(people2)
                .map(People::getTags)
                .map(s->s.stream()
                .map(People::getName)
                .collect(Collectors.toList())).ifPresent(per-> System.out.println(per));
    }

并发:

stream替换成parallelStream或 parallel

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值