遍历列表元素赋值给另一个列表

初级写法:

@PostMapping("/log")
public RestResponse<List<UserEventLogVM>> log(){
    // 获取当前对象
    User user = getCurrentUser();
    // 根据用户id查找用户行为日志
    List<UserEventLog> userEventLogs = userEventLogService.getUserEventLogByUserId(user.getId());
    // 将数据转换成视图对象
    List<UserEventLogVM> userEventLogVMS = new ArrayList<>();
    for (UserEventLog log : userEventLogs) {
        UserEventLogVM vm = new UserEventLogVM();
        vm.setId(log.getId());
        vm.setUserId(log.getId());
        vm.setUserName(log.getUserName());
        vm.setRealName(log.getRealName());
        vm.setContent(log.getContent());
        vm.setCreateTime(DateTimeUtil.dateFormat(log.getCreateTime()));
        userEventLogVMS.add(vm);
    }
    return RestResponse.ok(userEventLogVMS);
}

进阶写法:

@PostMapping("/log2")
public RestResponse<List<UserEventLogVM>> log2(){
    // 获取当前对象
    User user = getCurrentUser();
    // 根据用户id查找用户行为日志
    List<UserEventLog> userEventLogs = userEventLogService.getUserEventLogByUserId(user.getId());
    // 将数据转换成视图对象
    List<UserEventLogVM> userEventLogVMS = new ArrayList<>();
    for (UserEventLog log : userEventLogs) {
        UserEventLogVM vm = new UserEventLogVM();
        BeanUtils.copyProperties(log, vm);
        vm.setCreateTime(DateTimeUtil.dateFormat(log.getCreateTime()));
        userEventLogVMS.add(vm);
    }
    return RestResponse.ok(userEventLogVMS);
}

高级写法:

@PostMapping("/log3")
public RestResponse<List<UserEventLogVM>> log3() {
    // 获取当前用户
    User user = getCurrentUser();
    // 根据用户id查找用户行为日志
    List<UserEventLog> userEventLogs = userEventLogService.getUserEventLogByUserId(user.getId());
    // 将数据转换成视图对象
    List<UserEventLogVM> userEventLogVMS = userEventLogs.stream().map(d -> {
        UserEventLogVM vm = modelMapper.map(d, UserEventLogVM.class);
        vm.setCreateTime(DateTimeUtil.dateFormat(d.getCreateTime()));
        return vm;
    }).collect(Collectors.toList());
    return RestResponse.ok(userEventLogVMS);
}

你可能感兴趣的:(java,spring,boot,后端)