Java SE 学习笔记(Lambda表达式与Stream API)

1、 Lambda 表达式

2、 函数式(Functional)接口

3、 方法引用与构造器引用

4、 Stream API

方法

返回类型

作用

toList

List<T>

把流中元素收集到List

List<Employee> emps= list.stream().collect(Collectors.toList());

toSet

Set<T>

把流中元素收集到Set

Set<Employee> emps= list.stream().collect(Collectors.toSet());

toCollection

Collection<T>

把流中元素收集到创建的集合

Collection<Employee> emps =list.stream().collect(Collectors.toCollection(ArrayList::new));

counting

Long

计算流中元素的个数

long count = list.stream().collect(Collectors.counting());

summingInt

Integer

对流中元素的整数属性求和

int total=list.stream().collect(Collectors.summingInt(Employee::getSalary));

averagingInt

Double

计算流中元素Integer属性的平均值

double avg = list.stream().collect(Collectors.averagingInt(Employee::getSalary));

summarizingInt

IntSummaryStatistics

收集流中Integer属性的统计值。如:平均值

int SummaryStatisticsiss= list.stream().collect(Collectors.summarizingInt(Employee::getSalary));

joining

String

连接流中每个字符串

String str= list.stream().map(Employee::getName).collect(Collectors.joining());

maxBy

Optional<T>

根据比较器选择最大值

Optional<Emp>max= list.stream().collect(Collectors.maxBy(comparingInt(Employee::getSalary)));

minBy

Optional<T>

根据比较器选择最小值

Optional<Emp> min = list.stream().collect(Collectors.minBy(comparingInt(Employee::getSalary)));

reducing

归约产生的类型

从一个作为累加器的初始值开始,利用BinaryOperator与流中元素逐个结合,从而归约成单个值

int total=list.stream().collect(Collectors.reducing(0, Employee::getSalar, Integer::sum));

collectingAndThen

转换函数返回的类型

包裹另一个收集器,对其结果转换函数

int how= list.stream().collect(Collectors.collectingAndThen(Collectors.toList(), List::size));

groupingBy

Map<K, List<T>>

根据某属性值对流分组,属性为K,结果为V

Map<Emp.Status, List<Emp>> map= list.stream()

  .collect(Collectors.groupingBy(Employee::getStatus));

partitioningBy

Map<Boolean, List<T>>

根据truefalse进行分区

Map<Boolean,List<Emp>> vd = list.stream().collect(Collectors.partitioningBy(Employee::getManage));

发布了284 篇原创文章 · 获赞 45 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/qq_31784189/article/details/104222165