Java 项目经典代码

Java 项目经典代码

这里主要是记录在编写代码过程中经常使用的通用方法等,方便以后查阅!!!

一、逗号分割的字符串

 /**
     * 根据逗号分割,多个typeCode的字符串,返回对应的名称
     *
     * @param config
     * @return
     */
    private String getTypeNames(AlertFocusConfig config) {
        String typeName = "";
        if (StringUtils.hasText(config.getConcernType())) {
            String[] split = config.getConcernType().split(Constants.COMMA);
            for (String type : split) {
                typeName += StringUtils.hasText(typeName) ? Constants.COMMA + AlertFocusTypeEnum.getValueByKey(type) : AlertFocusTypeEnum.getValueByKey(type);
            }
        }
        return typeName;
    }

二、排序字段

      List<String> orderList = new ArrayList<>();
        sort.stream().forEach(e -> {
            orderList.add(e.getProperty());
            orderList.add(e.getDirection().toString());
        });
        if (Objects.isNull(queryDto)) {
            queryDto = new FacilityMaintenanceQueryDTO();
        }
        QueryWrapper<FacilityMaintenanceQueryDTO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(queryDto.getFacilityClassId()), "facility_class_id", queryDto.getFacilityClassId());
        PageUtils.transferSort(queryWrapper, sort);
   List<FacilityMaintenanceVO> maintenanceAllList = facilityMaintenanceMapper.getFacilityMaintenanceAllList(queryDto, orderList.get(0), orderList.get(1));

三、时间查询

  //养护到期时间-条件查询
     String startDate = queryDto.getStartDate();
        String endDate = queryDto.getEndDate();
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            mainVoList = mainVoList.stream().filter(e -> {
                DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate startDate1 = LocalDate.parse(startDate, fmt);
                LocalDate endDate1 = LocalDate.parse(endDate, fmt);
                //在开始日期之后,在结束日期之前
                if (Objects.nonNull(e.getDefaultMaintainDate())) {
                    if (!(startDate1.isAfter(e.getDefaultMaintainDate()) && endDate1.isBefore(e.getDefaultMaintainDate()))) {
                        return false;
                    }
                }
                return true;
            }).collect(Collectors.toList());
        }
        for (FacilityMaintenanceVO vo : mainVoList) {
            System.out.println(vo);
        }

四、日期比较

        //判断是否预警
//        mainVoList.stream().forEach(e -> {
//            //到期时间要比现在时间晚
//            if (LocalDate.now().isBefore(e.getEndDate())) {
//                e.setIsWarning(false);
//            } else {
//                e.setIsWarning(true);
//            }
//        });

四、stream 根据某个字段过滤

通用方法

  private static <T> Predicate<T> distinctByField(Function<? super T, ?> fieldExtractor) {
        Map<Object, Boolean> map = new ConcurrentHashMap<>(16);
        return t -> map.putIfAbsent(fieldExtractor.apply(t), Boolean.TRUE) == null;
    }

运用实例

  List<FacilityMaintenanceVO> maintenanceVoList = pageRecord.getRows().stream().filter(distinctByField(FacilityMaintenanceVO::getFacilityId)).collect(Collectors.toList());

测试代码

Student 类
package com.example.demotest;

import lombok.Data;

/**
 * @author wanglin
 * @version 1.0
 * @date 2022-03-16 周三
 */
@Data
public class Student {
    private String name;
    private String address;
    private Integer age;
    private Double score;
    public Student() {

    }
    public Student(String name, String address, Integer age, Double score) {
        this.name = name;
        this.address = address;
        this.age = age;
        this.score = score;
    }
}

DistinctTest 测试类
package com.example.demotest;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * @author wanglin
 * @version 1.0
 * @date 2022-03-16 周三
 */
public class DistinctTest {
    public static void main(String[] args) {
        Student stu1 = new Student();
        stu1.setName("小华");
        stu1.setAge(22);
        Student stu2 = new Student();
        stu2.setName("小华");
        stu2.setAge(25);
        Student stu3 = new Student();
        stu3.setName("小李");
        stu3.setAge(19);
        List<Student> students = new ArrayList();
        students.add(stu1);
        students.add(stu2);
        students.add(stu3);
        System.out.println("去重前:");
        students.stream().forEach(x->System.out.println(x.toString()));
        System.out.println("去重后");

        students.stream().filter(distinctByField(student -> student.getName())).forEach(x->System.out.println(x.toString()));
    }

    static <T> Predicate<T> distinctByField(Function<? super T,?> fieldExtractor){
        Map<Object,Boolean> map = new ConcurrentHashMap<>(16);
        return t -> map.putIfAbsent(fieldExtractor.apply(t), Boolean.TRUE) == null;
    }
}
测试结果

在这里插入图片描述

五、多字段唯一性验证

保存

 @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(ProcessDTO dto) {
        dto.setId(null);
        Server serverEntity = serverMapper.selectById(dto.getServerId());
        Assert.notNull(serverEntity, "服务器id不存在");

        //进程名称、path不能重复,如:"D:/test/test.pid
        List<Process> processList = validateRepeat(dto.getName(), dto.getPath());
        if (!processList.isEmpty()) {
            //2- 唯一性验证 ,name
            processList.stream().forEach(e -> {
                if (dto.getName().equals(e.getName())) {
                    CustomException.throwException("进程名称: " + dto.getName() + "已存在");
                }
                if (dto.getPath().equals(e.getPath())) {
                    CustomException.throwException("进程ID路径: " + dto.getPath() + "已存在");
                }
            });
        }
        processMapper.insert(this.transferEntity(null, dto));
    }

   

修改

 @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(ProcessDTO dto) {
        Assert.hasText(dto.getId(), "id不能为空");
        Process entity = processMapper.selectById(dto.getId());
        Assert.notNull(entity, "找不到id为 " + dto.getId() + " 的记录");
        // 唯一性字段校验
        List<Process> list = validateRepeat(dto.getName(), dto.getPath());
        list.stream().forEach(e -> {
            if (e.getName().equals(dto.getName())) {
                Assert.isTrue(dto.getId().equals(e.getId()), "名称: " + dto.getName() + "已存在");
            }
            if (e.getPath().equals(dto.getPath())) {
                Assert.isTrue(dto.getId().equals(e.getId()), "路径: " + dto.getPath() + "已存在");
            }
        });
        processMapper.updateById(this.transferEntity(entity, dto));
    }

公共代码

private List<Process> validateRepeat(String name, String path) {
        QueryWrapper<Process> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(StringUtils.isNotBlank(name), Process::getName, name)
                .or().eq(StringUtils.isNotBlank(path), Process::getPath, path);
        return processMapper.selectList(queryWrapper);
    }

关注林哥,持续更新哦!!!★,°:.☆( ̄▽ ̄)/$:.°★ 。

  • 1
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值