Stream中的函数

stream中的筛选函数

@Test
    public void TestAllMatch() {
        List<Dish> list = Arrays.asList(new Dish(true,new BigDecimal(125), 460 , "lufei"),
                new Dish(true,new BigDecimal(125), 245, "suolong"),
                new Dish(true,new BigDecimal(125), 496, "buluke"),
                new Dish(true,new BigDecimal(125), 479, "luobing"),
                new Dish(true,new BigDecimal(150), 125, "shenpin"),
                new Dish(false,new BigDecimal(129), 399, "namei"),
                new Dish(true,new BigDecimal(128),99, "wusuopu"));
        boolean flag = list.stream().allMatch(l -> l.getCalories() >100);
        boolean flag1 = list.stream().noneMatch(l -> l.getCalories() <=100);
        boolean flag2 = list.stream().anyMatch(l -> l.getCalories() <=100);
        System.out.println(flag);
        System.out.println(flag1);
        System.out.println(flag2);
    }

-----------------------------------------------------------------------------------------

stream中的求和函数

@Test
    public void testReduce() {
        List<Integer> nums = Arrays.asList(3, 4, 5, 6, 7);
        int result = nums.stream().reduce(1, (a, b) -> a*b);
        int result1 = nums.stream().reduce(0, (a, b) -> a+b);
        int result2 = nums.stream().reduce(0,Integer::sum);
        System.out.println(result);
        System.out.println(result1);
        System.out.println(result2);
    }

------------------------------------------------------------------------------------------

stream中最大值最小值

@Test
    public void testReduceMax() {
        List<Integer> nums = Arrays.asList(3, 4, 5, 6, 7);
        Optional<Integer> result = nums.stream().reduce(Integer::max);
        Optional<Integer> result1 = nums.stream().reduce(Integer::min);
        Optional<Integer> result2 = nums.stream().reduce((Integer a, Integer b)->a<b?a:b);
        System.out.println(result);
        System.out.println(result1);
        System.out.println(result2);
    }

----------------------------------------------------------------------------------------

Optional简介
Optional<T>类(java.util.Optional)是一个容器类,代表一个值存在或不存在。在
上面的代码中,findAny可能什么元素都没找到。Java 8的库设计人员引入了Optional<T>,这
样就不用返回众所周知容易出问题的null了。我们在这里不会详细讨论Optional,因为第10章
会详细解释你的代码如何利用Optional,避免和null检查相关的bug。不过现在,了解一下Optional里面几种可以迫使你显式地检查值是否存在或处理值不存在的情形的方法也不错。
 isPresent()将在Optional包含值的时候返回true, 否则返回false。
 ifPresent(Consumer<T> block)会在值存在的时候执行给定的代码块。我们在第3章
介绍了Consumer函数式接口;它让你传递一个接收T类型参数,并返回void的Lambda
表达式。
 T get()会在值存在时返回值,否则抛出一个NoSuchElement异常。
 T orElse(T other)会在值存在时返回值,否则返回一个默认值。

 

 

转载于:https://my.oschina.net/u/3589048/blog/1486844

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值