java8 之流式编程

java8 之流式编程

1.Lambda 表达式

格式描述:

左侧: Lambda 表达式的参数列表

右侧: Lambda 表达式所需执行的功能

中间: -> 箭头链接

四大内置函数式:

    List<Persion> getList() {
        List<Persion> list = Arrays.asList(
                new Persion("张思博", 18, "男", "阜阳", "后端", 8888),
                new Persion("沈超越", 19, "男", "阜阳", "前段", 0.5),
                new Persion("荣帅", 20, "男", "合肥", "前段", 10000),
                new Persion("文艳平", 21, "女", "合肥", "ios", 10000),
                new Persion("徐壮壮", 22, "男", "安庆", "测试", 10000),
                new Persion("刘康宁", 23, "男", "安庆", "dba", 10000),
                new Persion("钱悠悠", 24, "女", "芜湖", "测试", 10000)
        );
        return list;
    }
表达式一 : 有参数 无返回值
Consumer<T> consumer

示例:

@Test
    void test1() {
        List<Persion> persionList = getList();
        consumerDemo(persionList,x->x.setBalance(x.getBalance()*2));
        for (Persion persion : persionList) {
            System.out.println(persion);
        }
    }

    void consumerDemo(List<Persion> persionList,Consumer<Persion> consumer){
        for (Persion persion : persionList) {
            consumer.accept(persion);
        }
    }
表达式二: 无参数又返回值
Supplier<T> supplier

示例:

 @Test
    void test2(){
        List<Integer> random = getRandom(5, () -> (int) (Math.random() * 100));
        for (Integer integer : random) {
            System.out.println(integer);
        }
    }

    List<Integer> getRandom(int num,Supplier<Integer> supplier){
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            list.add(supplier.get());
        }
        return list;
    }
表达式三: 有参 有返回值
Function<T, R> function

示例:

@Test
    void test3() {
        Function<Integer,Integer> function = (x)->x*x;
        Integer apply = function.apply(3);
        System.out.println(apply);
        System.out.println("====================分割==========================");

        List<Persion> persionList = getList();
        List<String> nameList = functionTest(persionList, x -> x.getName());
        for (String s : nameList) {
            System.out.println(s);
        }
    }

    List<String> functionTest(List<Persion> list, Function<Persion, String> function) {
        List<String> beanList = new ArrayList<>();
        for (Persion bean : list) {
            String apply = function.apply(bean);
            beanList.add(apply);
        }
        return beanList;
    }
表达式四: 有参 有返回值
Predicate<T> predicate

示例:

@Test
    void test4(){
        List<Persion> list = getList();
        //余额
      List<Persion>  list1 =  predicateDemo(list,x->x.getBalance()>300);
        list1.forEach(System.out::println);
        System.out.println("================================================================");
        // 性别
        List<Persion>  list2 =  predicateDemo(list,x->"女".equals(x.getSex()));
        list2.forEach(System.out::println);
        System.out.println("================================================================");
        List<Persion>  list3 =  predicateDemo(list,x->"女".equals(x.getSex())&&x.getBalance()>300);
        list3.forEach(System.out::println);
    }
    List<Persion> predicateDemo(List<Persion> list, Predicate<Persion> predicate){
        List<Persion>  persionList = new ArrayList<>();
        list.forEach(bean->{
            boolean test = predicate.test(bean);
            if(test){
                persionList.add(bean);
            }
        });
      return  persionList;
    }

2.Stream 流

Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。

Stream API可以极大提高Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。

这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等。

元素流在管道中经过中间操作(intermediate operation)的处理,最后由最终操作(terminal operation)得到前面处理的结果。

+--------------------+       +------+   +------+   +---+   +-------+
| stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect|
+--------------------+       +------+   +------+   +---+   +-------+

在 Java 8 中, 集合接口有两个方法来生成流:

  • stream() − 为集合创建串行流。
  • parallelStream() − 为集合创建并行流。
forEach
forEach 迭代流中的每个数据
    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }	
map
map 方法用于映射每个元素到对应的结果
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
    @Test
    void test1(){
        // 收集 姓名
        List<String> collect1 = getList().stream().map(bean -> bean.getName()).collect(Collectors.toList());
        collect1.forEach(System.out::println);
        System.out.println("======================================");
        // 收集 城市
        List<String> collect2 = getList().stream().map(bean -> bean.getCity()).collect(Collectors.toList());
        collect2.forEach(System.out::println);
    }
filter
filter 方法用于通过设置的条件过滤出元素
Stream<T> filter(Predicate<? super T> predicate);
    @Test
    void test2(){
        // 过滤城市合肥
        List<Persion> collect1 = getList().stream().filter(x->x.getCity().equals("合肥")).collect(Collectors.toList());
        collect1.forEach(System.out::println);
        System.out.println("======================================");
        // 过滤性别是女
        List<Persion> collect2 =                   getList().stream().filter(x>x.getSex().equals("女")).collect(Collectors.toList());
        collect2.forEach(System.out::println);
    }
sorted
sorted 排序
    @Test
    void test3(){
        // Comparator.reverseOrder()降序
        // 按照年龄降/升
        List<Persion> collect = getList().stream().sorted(Comparator.comparing(Persion::getAge,Comparator.reverseOrder())).collect(Collectors.toList());
        collect.forEach(System.out::println);
        // 按照年龄 再按照 余额
        System.out.println("===============================================");
        List<Persion> collect2 = getList().stream().sorted(Comparator.comparing(Persion::getAge).thenComparing(Persion::getBalance,Comparator.nullsFirst(Double::compareTo))).collect(Collectors.toList());
        collect2.forEach(System.out::println);
    }
reduce
reduce 归约函数
  @Test
    void test4(){
        List<Integer> lists = new ArrayList<>();
        lists.add(10);
        lists.add(15);
        lists.add(20);
        lists.add(4);
        lists.add(5);
        lists.add(6);
        Integer reduce = lists.stream().reduce(1, (x, y) -> {
            System.out.println(x+"==="+y);
            return x+y;
        });
        System.out.println(reduce);
        System.out.println("================================");
        // 计算工资总和
        Double sum = getList().stream().map(x -> x.getBalance()).reduce(0d,(x,y)->{
            if(y==null){
                y =0d;
            }
            return  x+y;
        });
        System.out.println(sum);

    }
collect
collect 收集器
    @Test
    void test5(){
        // 工资总和
        Double collect1 = getList().stream().collect(Collectors.summingDouble(x -> x.getBalance() == null ? 0 : x.getBalance()));
        System.out.println(collect1);
        System.out.println("==================================");
        //平局工资
        Double collect = getList().stream().collect(Collectors.averagingDouble(x -> x.getBalance()==null?0:x.getBalance()));
        System.out.println(collect);
        System.out.println("=====================================");
        // summarizingDouble 指定某个元素的所有的操作
        DoubleSummaryStatistics collect2 = getList().stream().collect(Collectors.summarizingDouble(x -> x.getBalance() == null ? 0 : x.getBalance()));
        System.out.println(collect2);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值