Lambda是一个匿名函数,我们可以理解为是一段可以传递的代码,使代码更简洁灵活紧凑
Consumer consumer1 = (x) -> System.out.println(x); Consumer里面有一个accept接口要实现,提前写这个实现方法
consumer1.accept(new Employee());
从下往上看好理解
//一、获取对象集合里面a属性满足条件的第一个对象的b属性(相当于循环对象集合,满足条件即break)
String cpoCredentialsUrl = endpointVOList.stream()
.filter(endpointVO -> ModuleIDEnum.credentials.name().equalsIgnoreCase(endpointVO.getIdentifier()))
.findFirst()
.map(EndpointVO::getUrl).get();
//二、集合转集合
1、List<core> core = coresList.stream().filter((e) -> Objects.equals(e.getCoreRouteId(),"1")).collect(Collectors.toList());
2、Set<Long> userIds = orderList.stream()
.filter(chargeDetailRecordBill -> org.apache.commons.lang3.StringUtils.isNotBlank(chargeDetailRecordBill.getPlatform()))
.map(ChargeDetailRecordBill::getUserId)
.collect(Collectors.toSet());
3、List<String> ipcdIds = ieds.stream().map(Ied::getIedIpcdDeviceId).filter(Objects::nonNull).collect(Collectors.toList());
4、List<OpLocationEvseRealTimeDTO> opLocationEvseRealTimeDTOList = evseEntities.stream().map(entity -> {
OpLocationEvseRealTimeDTO opLocationEvseRealTimeDTO = OpLocationEvseConvert.toOpLocationEvseRealTimeDTO(entity);
opLocationEvseRealTimeDTO.setState(opLocationEvseRedis.getEvseStatus(entity.getId()).getName());
Map<String, String> monitorMap = opLocationEvseRedis.getEvseMonitorInfo(entity.getId());
OpLocationEvseConvert.setDataFromMap(opLocationEvseRealTimeDTO, monitorMap);
return opLocationEvseRealTimeDTO;
}).collect(Collectors.toList());
//三、集合转map
1、Map<String, ChargeStatisticsInfoDTO> dataMap = dataList.stream().collect(Collectors.toMap(ChargeStatisticsInfoDTO::getDateTime, Function.identity()));
2、Map<String, String> collect = endpointVOList.stream().collect(Collectors.toMap((endpointVO)-> endpointVO.getIdentifier().toUpperCase(), EndpointVO::getUrl));
3、Map<String, ChargeStatisticsInfoDTO> dataMap = dataList.stream()
.filter((chargeStatisticsInfoDTO) -> chargeStatisticsInfoDTO.getDateTime() != null)
.collect(Collectors.toMap(ChargeStatisticsInfoDTO::getDateTime, Function.identity()));
案例 加 stream
//遍历调用SysUser类里面的sysUserMethod()方法
userList.stream().map(SysUser::sysUserMethod)
//如果sysUserMethod有返回值,再后面再加上.collect(Collectors.toList())获取返回值
userList.stream().map(SysUser::sysUserMethod).collect(Collectors.toList());
(接口参数,实现类)左侧存放表达式的参数列表(相当于接口的参数列表),右侧存放表达式所需执行的功能(相当于实现类的方法)
public class TestDemo1 {
//语法1:无参数无返回值
@Test
public void test1(){
Runnable runnable2 = () -> System.out.println("Lambda打印内容1");
runnable2.run();
}
//语法2:有一个参数,无返回值
@Test
public void test2(){
Consumer<Employee> consumer1 = (x) -> System.out.println(x);
consumer1.accept(new Employee());
}
//语法3:多个参数,有返回值,并且方法体有多个语句
@Test
public void test3(){
Comparator<Employee> comparator1 = (X,Y) -> {
System.out.println("Lambda打印内容3");
return 0;
};
comparator1.compare(new Employee(),new Employee());
}
//语法4:方法体只有一条语句时,方法体和return语句都可以不行
@Test
public void test4(){
Comparator<Integer> comparator1 = (x,y) -> Integer.compare(x,y);
int compare = comparator1.compare(1, 2);
System.out.println(compare);
}
//语法5:Lambda表达式的参数类型可以省略不写,因为jvm可以通过上下文推断出,即"类型推断"
//优化方式四:只需要实体类和一个List
employeeList.stream()
.filter( (e) -> e.getAge() >=15 )
.forEach(System.out::println);
}
案例一。根据Id查询用户(先查redis,再查sql)
//getObjectById方法需要两个参数userId和User,第二个参数通过函数返回值来传递
@Override
public User getUserByIdTemplate(Integer userId) {
User user = moduleTemplate.getObjectById(userId,() ->{
//查询数据库
return getUserById(userId);
});
return user;
}
案例二 遍历
ids.forEach(publishId -> {
discoverPublishRepository.deleteByPrimaryKey(publishId);
});
案例三。查出年龄大于15的所有员工
//2.Lambda调用
List<Employee> employees3 = filterEmployee(employeeList, (e) -> e.getAge() == 15);
//1、模板方法
public static List<Employee> filterEmployee(List<Employee> list,MyPredicate<Employee> mp){
List<Employee> resultList = new ArrayList<>();
for (Employee employee:list){
if (mp.test(employee)){
resultList.add(employee);
}
}
return resultList;
}
//四种优化方式,在github/lambda
package com.test;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainApplication {
private static List<Employee> employeeList = Arrays.asList(
new Employee("张三",13,3000),
new Employee("李四",14,4000),
new Employee("王五",15,5000),
new Employee("赵六",16,6000),
new Employee("田七",17,7000)
);
public static void main(String[] args) {
//打印出所有
employeeList.forEach(employee -> System.out.println("所有-----" + employee));
//优化方式一:策略模式
List<Employee> employees1 = filterEmployee(employeeList, new FilterEmployeeByAge());
employees1.forEach(employee -> System.out.println("策略模式-----" +employee));
//优化方式二:匿名内部类
List<Employee> employees2 = filterEmployee(employeeList, new MyPredicate<Employee>() {
@Override
public boolean test(Employee employee) {
if (employee.getSalary() <= 5000){
return true;
}
return false;
}
});
employees1.forEach(employee -> System.out.println("匿名内部类-----" +employee));
//优化方式三:Lambda
List<Employee> employees3 = filterEmployee(employeeList, (e) -> e.getAge() == 15);
employees3.forEach(employee -> System.out.println("Lambda方法-----" +employee));
//优化方式四:只需要实体类和一个List
employeeList.stream()
.filter( (e) -> e.getAge() >=15 )
.forEach(System.out::println);
}
//策略模式方法
public static List<Employee> filterEmployee(List<Employee> list,MyPredicate<Employee> mp){
List<Employee> resultList = new ArrayList<>();
for (Employee employee:list){
if (mp.test(employee)){
resultList.add(employee);
}
}
return resultList;
}
}
双冒号 ::
引用对象的方法
引用对象的方法
userList.forEach(SysUser::getUserName);