Lambda 双冒号:: 流式编程

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();


//二、集合转集合
	1List<core> core = coresList.stream().filter((e) -> Objects.equals(e.getCoreRouteId(),"1")).collect(Collectors.toList());
	2Set<Long> userIds = orderList.stream()
                .filter(chargeDetailRecordBill -> org.apache.commons.lang3.StringUtils.isNotBlank(chargeDetailRecordBill.getPlatform()))
                .map(ChargeDetailRecordBill::getUserId)
                .collect(Collectors.toSet());
	3List<String> ipcdIds = ieds.stream().map(Ied::getIedIpcdDeviceId).filter(Objects::nonNull).collect(Collectors.toList());
	4List<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
	1Map<String, ChargeStatisticsInfoDTO> dataMap = dataList.stream().collect(Collectors.toMap(ChargeStatisticsInfoDTO::getDateTime, Function.identity()));
	2Map<String, String> collect = endpointVOList.stream().collect(Collectors.toMap((endpointVO)-> endpointVO.getIdentifier().toUpperCase(), EndpointVO::getUrl));
	3Map<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);
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

飘然生

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

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

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

打赏作者

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

抵扣说明:

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

余额充值