首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JDK8-Lambda表达式集合操作

JDK8-Lambda表达式集合操作

作者头像
tanoak
发布2018-08-21 15:18:52
4590
发布2018-08-21 15:18:52
举报
文章被收录于专栏:java闲聊java闲聊

Lambda表达式理解为简洁地表示可传递的匿名函数的一种方式:

它没有名称,但它有参数列表、函数主体、返回类型,可能还有一个可以抛出的异常列表

Lambda的使用场景多用于集合

  1. 流 流是Java API的新成员,它允许你以声明性方式处理数据集合,简而言之,可以把它们看成遍历数据集的高级迭代器。此外,流还可以透明地并行处理,无需写任何多线程代码
    • pojo public class Dish { private String name; private Integer calories; private Double price ; public Dish(){ } public Dish(String name , Integer calories,Double price) { this.name = name; this.calories = calories; this.price=price ; } }
    • 测试数据

    public static List<Dish> toLists(){ return Arrays.asList( new Dish("青菜", 700,800.0), new Dish("黄瓜", 700 ,300.0), new Dish("鱼香肉丝", 2000 ,400.0), new Dish("红烧土豆", 730 ,400.0), new Dish("土豆丝", 850 ,600.0), new Dish("红烧鱼", 3000 ,3000.0), new Dish("西红柿鸡蛋", 1050 ,600.0), new Dish("炒三鲜", 1300 ,800.0), new Dish("竹笋炒肉", 2450,1000.0 ) ); } public static List<Integer> toNumbers(){ return Arrays.asList(1,2,3,4); }

    • 筛选操作 ​ filter()过滤、 distinct() 它会返回一个元素的流 @Test public void test(){//以菜名大于3位数的过滤,选择3条数据并输出 toLists().stream().filter(d->d.getName().length()>3).limit(3).distinct().forEach(s-> System.out.println(s)); }
    • 查找匹配操作 ​ StreamAPI通过 allMatch 、 anyMatch 、 noneMatch 、 findFirst 和 findAny 方法提供了这样的工具。某些操作不用处理整个流就能得到结果。只要找到一个元素,就可以有结果 @Test public void test2(){//菜单中所有菜色价格是否全都2000元以上 Boolean temp = toLists().stream().allMatch(d->d.getPrice()>2000); System.out.println(temp);// 满足条件 true 否则 false } @Test public void test3(){//找到第一个数据,直接返回 Optional<Dish> any = toLists().stream().filter(s -> s.getName().length() > 2).findAny(); System.out.println(any); }
      • 归约 ​ 把一个流中的元素组合起来,使用 reduce 操作来表达更复杂的查询 reduce 接受两个参数: 一个初始值,这里是0; 一个 BinaryOperator<T> 来将两个元素结合起来产生一个新值 @Test public void test4(){ Integer sum = toNumbers().stream().reduce(0, Integer::sum) ; // System.out.println(sum); int product = toNumbers().stream().reduce(1, (a, b) -> a * b); System.out.println(product); /*int count = toLists().stream() .map(d -> 1) .reduce(0, (a, b) -> a + b); System.out.println(count);*/ }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.08.19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档