一、Lambda
1.语法结构
// 1. 不需要参数,返回值为1
() -> 1
// 2. 接收一个参数(数字类型),返回其2倍的值
x -> 2 * x
// 3. 接受2个参数(数字),并返回他们的差值
(x, y) -> x – y
// 4. 接收2个int型整数,返回他们的和
(int x, int y) -> x + y
// 5. 接受一个String对象,并在控制台打印,不返回任何值(看起来像是返回void)
(String s) -> System.out.println(s)
2.双冒号::
类::静态方法
Person::getName
类::构造方法
Person::new
System.out::println
数组类型::new
String[]::new
二、Stream流
集合
List list = new ArrayList<>();
list.add(new Person(“张三”,18));
list.add(new Person(“小明”,16));
list.add(new Person(“小红”,22));
1.过滤数据
// 只留下张三的数据
List filterList = list.stream().filter(o -> o.getName() == “张三”).collect(Collectors.toList());
// 单个对象
Person person= list.stream().filter(p -> p.getAge() > 21).findFirst();
2-1.排序-默认升序
List sortedList1 = list.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());
2-2.排序-降序
List sortedList2 = list.stream().sorted(Comparator.comparing(Person::getAge).reversed()).collect(Collectors.toList());
3.限制输出条数
List limitList = list.stream().limit(2).collect(Collectors.toList());
4.跳过前n个元素
List skipList = list.stream().skip(1).collect(Collectors.toList());
5.遍历
list.stream().forEach(item ->System.out.println(item.getName()));
6.去重
List distinctList = list.stream().distinct().collect(Collectors.toList());
7.map 映射每个元素到对应的结果
转换成String
String strName = list.stream().map(Person::getName).collect(Collectors.joining(“,”));
转换成Set集合
Set setName = list.stream().map(Person::getName).collect(Collectors.toSet());
转换成Vector
Vector vectorName = list.stream().map(Person::getName).collect(Collectors.toCollection(Vector::new));
转换成List
List listName = list.stream().map(Person::getName).collect(Collectors.toList());
转换成Map
Map<String, Integer> mapName = list.stream().collect(Collectors.toMap(Person::getName, Person::getAge));
Map<String, BigDecimal> map = list.stream().collect(Collectors.toMap(i -> i.getDepartCode(), i -> i.getTargetEfficiency(), (i1, i2) -> i1));
Map<Integer, **DTO> objectMap = list.stream().collect(Collectors.toMap(i -> i.getDepartId(), (i) -> i));
分组
Map<Long, List> map = list.stream().collect(Collectors.groupingBy(EstimateSale::getDepartId));
// GroupBy 本质是返回一个String(即map的key),所以若想要多个组合group,返回多个组合String即可
// 如departCode + spuCode 组合group
Map<String, List> map = list.stream()
.collect(Collectors.groupingBy(
i -> i.getDepartCode() + “:” + i.getSpuCode()
));
mapToInt
累加
int totalAge = list.stream().mapToInt(Person::getAge).sum();
平均值
double averageAge=list.stream().mapToInt(Person::getAge).average().getAsDouble();
最大值
int maxAge = list.stream().mapToInt(Person::getAge).max().getAsInt();
最小值
int minAge = list.stream().mapToInt(Person::getAge).min().getAsInt();