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);
}
关注林哥,持续更新哦!!!★,°:.☆( ̄▽ ̄)/$:.°★ 。