lambda表达式的使用(全)

大家应该都知道jdk8的lambda表达式了,还是比较好用的,下面介绍一下用法

Lambda简介

Lambda 表达式是 JDK8 的一个新特性,可以取代大部分的匿名内部类,写出更优雅的 Java 代码,尤其在集合的遍历和其他集合操作中,可以极大地优化代码结构。
JDK 也提供了大量的内置函数式接口供我们使用,使得 Lambda 表达式的运用更加方便、高效。
语法形式为 () -> {},其中 () 用来描述参数列表,{} 用来描述方法体,-> 为 lambda运算符 ,读作(goes to)。

Streams(流)

Stream有几个特性:

  • stream不存储数据,而是按照特定的规则对数据进行计算,一般会输出结果。
  • stream不会改变数据源,通常情况下会产生一个新的集合或一个值。
  • stream具有延迟执行特性,只有调用终端操作时,中间操作才会执行。

(聚集的时候用collect,对对象进行操作的时候用map)

Match(匹配)
stringList.sort((a,b)->a.compareTo(b));  //排序
boolean ret = stringList.stream().anyMatch(x->x.startsWith("a"));  
匹配

anyMatch表示,判断的条件里,任意一个元素成功,返回true
allMatch表示,判断条件里的元素,所有的都是,返回true
noneMatch跟allMatch相反,判断条件里的元素,所有的都不是,返回true

Filter(过滤)/count
long num = stringList.stream().filter(x->x.startsWith("b")).count();
List<Integer> list = Arrays.asList(3,2,67,9,1);
Integer i = list.stream().min(Integer::compareTo).get();
求和
double total = accountList.stream().mapToDouble(Account::getBalance).sum();
Parallel Streams(并行流)

并行流比串行流更快,但是需要注意使用场景是否有数据错乱的情况。那么什么时候使用parallelStream?

  • 注意list元素是否可并行处理?
  • 元素之间是否是独立的?
  • 是否有调用顺序的区分?
  • 若都没有则可以使用此流更加快速
//对象TestDTO
Map<String, List<TestDTO>> sortAppId = list.parallelStream().collect(
Collectors.groupingBy(TestDTO::getAppId));
//appid为对象的一个属性

//可用大括号具体操作
list.parallelStream().map(x -> {
    x.setOrderId(1);
    return x;
}).collect(Collectors.toList());
异步
public static void sync() throws Exception {
//异步执行
    CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
        }
        if(new Random().nextInt()%2>=0) {
            int i = 12/0;
        }
        System.out.println("run end ...");
    });
    
//异步完成回调
    future.whenComplete(new BiConsumer<Void, Throwable>() {
        @Override
        public void accept(Void t, Throwable action) {
            System.out.println("执行完成!");
        }
        
    });

//异步异常回调
    future.exceptionally(new Function<Throwable, Void>() {
        @Override
        public Void apply(Throwable t) {
            System.out.println("执行失败!"+t.getMessage());
            return null;
        }
    });
    
    TimeUnit.SECONDS.sleep(2);
}
map的使用
List<Employee> employees = initList();

List<Integer> employeeList = employees.stream().map(Employee::getId)
.collect(toList());

//提取为Map1
Map<Integer, Employee> idEmployeeMap = employees.stream().collect(
Collectors.toMap(Employee::getId, Function.identity()));

//提取为map2,value为List
Map<Integer, List<Employee>> departGroupMap = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartId));

//提取为map3,value为list下对象中的一个字段的集合
Map<Integer, List<String>> departNamesMap =employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartId,
Collectors.mapping(Employee::getName, Collectors.toList()))
);

//获取一个属性的集合
List<String> workIds = list.parallelStream().map(TestDTO::getWorkId)
.collect(Collectors.toList());


/**
 * List -> Map
 * 需要注意的是:
 * toMap 如果集合对象有重复的key,会报错Duplicate key ....
 *  apple1,apple12的id都为1。
 *  可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
 */
Map<Integer, Apple> appleMap = appleList.stream().collect(
Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));
max使用
Optional<Person> max = personList.stream()
    .max(Comparator.comparingInt(Person::getSalary));
stream的归约

多条归于一条

public class StreamTest {
 public static void main(String[] args) {
  List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);
  // 求和方式1
  Optional<Integer> sum = list.stream().reduce((x, y) -> x + y);
  // 求和方式2
  Optional<Integer> sum2 = list.stream().reduce(Integer::sum);
  // 求和方式3
  Integer sum3 = list.stream().reduce(0, Integer::sum);
  
  // 求乘积
  Optional<Integer> product = list.stream().reduce((x, y) -> x * y);

  // 求最大值方式1
  Optional<Integer> max = list.stream().reduce((x, y) -> x > y ? x : y);
  // 求最大值写法2
  Integer max2 = list.stream().reduce(1, Integer::max);

  System.out.println("list求和:" + sum.get() + "," + sum2.get() + "," + sum3);
  System.out.println("list求积:" + product.get());
  System.out.println("list求和:" + max.get() + "," + max2);
 }
}


// 求工资之和方式1:
Optional<Integer> sumSalary = personList.stream().map(Person::getSalary)
  .reduce(Integer::sum);
  
// 求工资之和
  Integer sum = personList.stream()
  .collect(Collectors.summingInt(Person::getSalary));


  // 求最高工资方式1:
Integer maxSalary = personList.stream()
      .reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
    Integer::max);
    
    // 求最高工资
Optional<Integer> max = personList.stream().map(Person::getSalary)
  .collect(Collectors.maxBy(Integer::compare));
Collectors

Collectors提供了一系列用于数据统计的静态方法:

计数:count

平均值:averagingInt、averagingLong、averagingDouble

最值:maxBy、minBy

求和:summingInt、summingLong、summingDouble

统计以上所有:summarizingInt、summarizingLong、summarizingDouble

// 求平均工资
  Double average = personList.stream()
  .collect(Collectors.averagingDouble(Person::getSalary));


// 一次性统计所有信息
DoubleSummaryStatistics collect = personList.stream()
.collect(Collectors.summarizingDouble(Person::getSalary));

返回
DoubleSummaryStatistics{count=3, sum=23700.000000,min=7000.000000, average=7900.000000, max=8900.000000}

分组
将员工按薪资是否高于8000分组
Map<Boolean, List<Person>> part = personList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));
// 将员工按性别分组
Map<String, List<Person>> group = personList.stream().collect(Collectors.groupingBy(Person::getSex));
// 将员工先按性别分组,再按地区分组
Map<String, Map<String, List<Person>>> group2 = personList.stream().collect(Collectors.
    groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
接合(joining)
//用逗号给集合中的名字连接起来
String names = personList.stream().map(p -> p.getName()).collect(Collectors.joining(","));
Collectors的归约

相比于stream本身的reduce方法,增加了对自定义归约的支持。

Sorted(排序)

有两种排序:

  • sorted():自然排序,流中元素需实现Comparable接口
  • sorted(Comparator com):Comparator排序器自定义排序
stringList.stream().map(String::toUpperCase).sorted((a,b)->a.compareTo(b)).forEach(System.out::println); 

// 按工资增序排序
List<String> newList = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName)
    .collect(Collectors.toList());
// 按工资倒序排序
List<String> newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed())
    .map(Person::getName).collect(Collectors.toList());
去重
stream().map(YxStoreProduct::getProductServerId).distinct().collect(Collectors.toList());

参考:https://mp.weixin.qq.com/s/WM4IfFcEilY3dGTfa2ap9g

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我是小酒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值