Java8实战——流的初识(一)

Java8已经出来很久,工作学习中总有部分代码使用的Lambda表达式,对于不怎么熟悉的人来说确实有阅读障碍,但是在实际工作中使用起来还是非常便的。

1、Lambda 管中窥豹

可以把Lambda表达式理解为简洁地表示可传递的匿名函数的一种方式:它没有名称,但它有参数列表、函数主体、返回类型,可能还有一个可以抛出的异常列表

(Apple a) -> "green".equals(a.getColor()
⬆         ⬆                ⬆
参数      箭头             主体

先前(筛选绿苹果)

    List<Apple> greenApple1 = new ArrayList<>();
        for (Apple apple : inventory) {
            Apple apple1 = new Apple();
            if("green".equals(apple.getColor())){
                apple1.setColor("green");
                apple1.setWeight(apple.getWeight());
                appleColor.add(apple1);
            }
        }

之后(筛选绿苹果)

 List<Apple> collect = inventory.stream()
                                .filter(apple -> "green".equals(apple.getColor()))
                                .collect(Collectors.toList());

通过filter()函数筛选,再用collect()转成所需要的对象。

  • 参数列表 —— 所需要的对象(命名可以自定义)
  • 箭头 ——将参数列表和主体分开
  • Lambda——比较Apple的颜色

2. 流是什么

流是Java API的新成员,它允许你以声明性方式处理数据集合(通过查询语句来表达,而不是临时编写一个实现)。就现在来说,你可以把它们看成遍历数据集的高级迭代器。此外,流还可以透明地并行处理,你无需写任何多线程代码了。

List<Dish> menu = Arrays.asList( 
  new Dish("pork", false, 800, Dish.Type.MEAT), 
  new Dish("beef", false, 700, Dish.Type.MEAT), 
  new Dish("chicken", false, 400, Dish.Type.MEAT), 
  new Dish("french fries", true, 530, Dish.Type.OTHER),
  new Dish("rice", true, 350, Dish.Type.OTHER), 
  new Dish("season fruit", true, 120, Dish.Type.OTHER), 
  new Dish("pizza", true, 550, Dish.Type.OTHER), 
  new Dish("prawns", false, 300, Dish.Type.FISH), 
  new Dish("salmon", false, 450, Dish.Type.FISH) );

//筛选出 400卡以下并且排序的菜名
List<String> lowCaloricDishesName =  menu.stream() 
                                         .filter(d -> d.getCalories() < 400) 
                                         .sorted(comparing(Dish::getCalories))
                                         .map(Dish::getName) 
                                         .collect(toList());
  • filter() 筛选400卡以下
  • sorted(comparing())从小到大
  • map()将元素转换成其他形式或提取信息    等于 String name = menu.getName(); 
  • collect()将流转换成其他形式

类似一个流水线操作。因为filter、sorted、map和collect等操作是与具体线程模型无关的高层次构件,所以
它们的内部实现可以是单线程的。无效考虑线程安全问题。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值