文章目录
Lambda表达式
语法
(arg1, arg2) -> expression
(arg1, arg2) -> {body}
- 箭头,函数参数列表与表达式/函数主体的分隔符
- Lambda表达式可包含0或多个参数
- 参数列表,当参数为空时,需声明空括号;当只有一个参数时,可省略括号;参数类型可省略,编译器自动完成类型推导
- Lambda 表达式的函数体,可包含0或多条语句
- 函数体,只有一条语句的表达式,可省略{}号;包含一条以上语句,必须包含在括号中(代码块);返回类型必须匹配;没有可不声明返回值
Stream流
基础知识
- 鉴于Java对集合操作的复杂性,Java8中引入Stream API,用于操作处理集合中的元素
- 集合是存储元素对象的容器
- Stream(集合流),并不是存储元素的数据结构,而是操作集合元素的管道
- Stream操作的是集合中的元素,而非集合本身。因此,将创建新集合聚合Stream操作的结果,而不影响原集合结构
- Stream仅会对流过的元素操作一次(流走了)(与Iterator的游标相似),因此,必须生成一个新Stream才能继续操作
- Collection接口中,通过stream()方法获取当前集合的Stream对象
中间 / 终止操作
中间操作(Intermediate Operations):对集合中元素的执行的具体操作
- Stream filter():基于参数选择stream中的元素,过滤
- Stream map():基于stream操作映射为新的类型,映射
- Stream sorted():排序stream中的元素,排序
- Long count():获取stream中元素个数,计数
中间操作执行后,将结果置入一个新Stream,从而允许基于新Stream实现后续操作,形成基于Stream的操作链。
终止操作(Terminal Operations):终止stream操作处理,消费stream操作产生的结果
- collect():聚合在stream中间操作的结果
- forEach():迭代stream的每个元素
代码
import java.sql.SQLOutput;
import java.util.*;
import java.util.stream.*;
class Apple{
private String color;
private Double weight;
Apple(String color, Double weight){
this.color=color;
this.weight=weight;
}
public String getColor() {
return color;
}
public Double getWeight() {
return weight;
}
}
public class Test {
public static void main(String[] args) {
Apple a = new Apple("red",23.5);
Apple b = new Apple("red",22.8);
Apple c = new Apple("red",21.7);
Apple d = new Apple("green",24.2);
ArrayList<Apple> apples = new ArrayList<>();
apples.addAll(List.of( new Apple[]{a,b,c,d}));
apples.stream().filter(i -> i.getColor() == "red" && i.getWeight() >= 22) //过滤
.map(Apple::getWeight) //映射
.forEach(System.out::println); //遍历
System.out.println("------");
apples.stream().sorted(Comparator.comparing(Apple::getWeight).reversed()) //逆序排列
.collect(Collectors.toList()) //聚合
.forEach(i -> System.out.println(i.getWeight()));
System.out.println("------");
Map<Double, Apple> appleMap = apples.stream().collect(Collectors.toMap(i -> i.getWeight(),i ->i)); //collect中toMap方法
appleMap.forEach((k,v) -> System.out.println(k+":"+v.getColor())); //forEach遍历Map
System.out.println("------");
apples.stream().collect(Collectors.groupingBy(Apple::getColor)) //collect中groupingBy方法
.forEach((k,v) -> System.out.println(k+":"+v.stream().map(Apple::getWeight).collect(Collectors.toList())));
System.out.println("------");
apples.removeIf(i -> i.getColor() == "red"); //移除指定元素
apples.stream().forEach(i -> System.out.println(i.getColor()));
}
}
执行结果:
23.5
22.8
------
24.2
23.5
22.8
21.7
------
21.7:red
23.5:red
22.8:red
24.2:green
------
red:[23.5, 22.8, 21.7]
green:[24.2]
------
green
Process finished with exit code 0
Stream filter()
过滤stream中元素,表达式结果必须为boolean值,为真置于新stream,为假过滤掉
Stream map()
映射Stream中元素,基于条件将元素映射为新类型元素
Stream sorted()
对stream中元素排序,其中:
Comparator类,比较器,控制顺序
- comparing(),基于指定值排序
- reversed(),倒序
T collect()
聚合,收集stream一系列中间操作产生的结果,其中:
Collectors(java.util.stream.Collectors)类,用于操作聚合结果的工具类
- groupingBy()/mapping()
groupingBy(),基于给定数据,以Map分组集合
- toList()/toSet()/toMap()
toMap(K, V),基于给定键值,以Map分组集合
Boolean removeIf()
Collection接口中定义,移除符合函数表达式的元素。底层依然基于Iterator迭代器实现
Stream的其他方法
- takeWhile(),获取位于第一个不满足给定条件的元素之前的所有元素
- dropWhile(),获取位于第一个不满足给定条件的元素及其之后的所有元素
- flatMap(),将多层映射合并
- findFirst(),从流中取第一个元素,封装到Optional
- findAny(),从流中取任意一个元素
- anyMatch(),任意一个元素符合条件,返回true
- allMatch(),全部元素符合条件,返回true
- distinct():去重
……
代码:
import java.util.*;
class Apple{
private String color;
private Double weight;
Apple(String color, Double weight){
this.color=color;
this.weight=weight;
}
public String getColor() {
return color;
}
public Double getWeight() {
return weight;
}
}
public class Test {
public static void main(String[] args) {
Apple a = new Apple("red",23.5);
Apple b = new Apple("red",22.8);
Apple c = new Apple("red",21.7);
Apple d = new Apple("green",24.2);
ArrayList<Apple> apples = new ArrayList<>();
apples.addAll(List.of( new Apple[]{a,b,c,d}));
apples.stream().takeWhile(i -> i.getWeight() >= 22).forEach(i -> System.out.println(i.getWeight())); //takeWhile()
System.out.println("------");
apples.stream().dropWhile(i -> i.getWeight() >=22).forEach(i -> System.out.println(i.getWeight())); //dropWhile()
System.out.println("------");
Apple apple01 = apples.stream().findFirst().get(); //findFirst()
System.out.println(apple01.getWeight());
Apple apple02 = apples.stream().findAny().get(); //findAny()
System.out.println(apple02.getWeight());
System.out.println("------");
Boolean istrue = apples.stream().anyMatch(i -> i.getColor()=="green"); //anyMatch()
Boolean isTrue = apples.stream().allMatch(i -> i.getColor() == "red"); //allMatch()
System.out.println(istrue + " "+ isTrue);
}
}
执行结果:
23.5
22.8
------
21.7
24.2
------
23.5
23.5
------
true false
Process finished with exit code 0