常用code

13 阅读3分钟

一、Stream

Map

[1] list 转 map,避免重复key, 重复时,使用第一个value

list.stream().collect(Collectors.toMap(People::getName, Function.identity(), (k, v) -> k));

[2] list 转 map,避免null value,null value会出错
systems.stream().collect(Collectors.toMap(ThingInfo::getId,
system -> StringUtils.isBlank(system.getProjectName()) ? "" : system.getProjectName(),
 (k, v) -> k));
 
【3】 遍历
for (Map.Entry<Integer, Integer> entry : map.entrySet()) { System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue()); }

过滤

[1] 
templates.stream().filter(template -> template.getColumnName().equals(column)).findFirst()
            .map(ReportHeadTemplate::getColumnType).orElse("")
         

Option

1、判断map结果不为空,再给对象set 属性值
Optional.ofNullable(userIdInfoMap.get(name))
            .ifPresent(userInfo -> evaluationInfo.setEvaluatorUser(userInfo.getName()));

2、集合判断 为空返回空集合                
List<String> list = null;
List<String> newList = Optional.ofNullable(list).orElse(new ArrayList());
newList.forEach(x -> System.out.println(x));
         

分组

1. 分组成map<key,bean>
Map<Long, List<OtaTaskVehicle>> vehicleListMap = vehicleList.stream()
                .collect(Collectors.groupingBy(veh -> veh.getTaskId()));
                
 2. 分组后提取对象中某个属性
Map<Long, Set<Long>> nodeIdMap = topologyNodes.stream()
            .collect(Collectors.groupingBy(
                TopologyNodeInfoSync::getThingId,  // 1. 按 thingId 分组
                Collectors.mapping(                // 2. 对每个分组内的元素进行映射
                    TopologyNodeInfoSync::getId,   // 2.1 提取 id
                    Collectors.toSet()             // 2.2 收集到 Set 中
                )
            ));    
         

三、运算

日期转换

DatePattern.NORM_DATE_PATTERN = "yyyy-MM-dd";
DatePattern.NORM_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

[1] 日期转字符串
当前时间 Date date = DateUtil.date(); 
// 结果 2020/01/24 
String format = DateUtil.format(date, "yyyy/MM/dd"); 

//常用格式的格式化,结果:2020-01-24 
String formatDate = DateUtil.formatDate(date); 

//结果:2020-01-24 17:25:02 
String formatDateTime = DateUtil.formatDateTime(date);


[2]  字符串转日期
String dateStr = "2017-03-01"; 
Date date = DateUtil.parse(dateStr, "yyyy-MM-dd");
         

日期计算

DatePattern.NORM_DATE_PATTERN = "yyyy-MM-dd";
DatePattern.NORM_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

[1] 日期转字符串
当前时间 Date date = DateUtil.date(); 
//常用格式的格式化,结果:2020-01-24 
String formatDate = DateUtil.formatDate(date); 
//结果:2020-01-24 17:25:02 
String formatDateTime = DateUtil.formatDateTime(date);

[2]  字符串转日期
String dateStr = "2017-03-01"; 
Date date = DateUtil.parse(dateStr, "yyyy-MM-dd");

-- 获取一天开始的时间 00:00
LocalDateTime cleanTaskEndTime.truncatedTo(ChronoUnit.DAYS)

日期加减
LocalDateTime cleanTaskEndTime.plusDays(1)
     
两日期 之间天数     
long daysBetween = Duration.between(cleanTaskEndTime.truncatedTo(ChronoUnit.DAYS), now).toDays();

两日期之间的每一天
private List<DateTime> between(DateTime start, DateTime end) {
        List<DateTime> dateTimes = new ArrayList<>();
        for (DateTime dateTime = start; dateTime.isBefore(end); dateTime = dateTime.offset(DateField.DAY_OF_MONTH, 1)) {
            dateTimes.add(dateTime);
        }
        // 添加结束日期(可选,取决于是否需要包含结束日期)
        dateTimes.add(end);
        return dateTimes;
    }

数字类

[1] 对 list 某个字段求和 
BigDecimal eForecastTotal = sumBigDecimalField(reportTags, CleaningReportTag::getEForecast);;

public static <T> BigDecimal sumBigDecimalField(List<T> list, Function<T, BigDecimal> fieldExtractor) {  
    // 1. 处理列表为 null 或空的情况  
    if (list == null || list.isEmpty()) {  
        return BigDecimal.ZERO;  
    }  
  
    // 2. 通用累加逻辑:提取字段 → 处理 null → 累加  
    return list.stream()  
            // 提取字段,null 则替换为 0            .map(item -> Optional.ofNullable(fieldExtractor.apply(item)).orElse(BigDecimal.ZERO))  
            // 累加所有值  
            .reduce(BigDecimal.ZERO, BigDecimal::add);  
}
         

对象

[1] 根据id填充List中name属性,map中取值
    waterDevices.stream().filter(waterDevice -> stationIdNameMap.containsKey(waterDevice.getProjectId()))  
            .forEach(waterDevice -> {  
                String projectName = stationIdNameMap.get(waterDevice.getProjectId());  
                waterDevice.setProjectName(projectName);  
            });  
         

json

1. json转成javabean
   
List<String> columns =
JacksonUtils.getJsonConvert().fromJsonList(userSelectionInfo.getInfoJson(), String.class);

集合

[1] 将List 拆成子list数量固定的多个 list , 每一个子List size是NUMBER_TWO
import com.google.common.collect.Lists; List<List<String>> partition = Lists.partition(initNumA(), NUMBER_TWO);


[2] 将List 拆成固定数量 子List  
public static <T> List<List<T>> splitListByNum(List<T> list, int parts) {
    List<List<T>> result = new ArrayList<>();
    int totalSize = list.size();

    // 每个子列表的平均大小
    int baseSize = totalSize / parts;
    // 计算多余的元素
    int remainder = totalSize % parts;

    int index = 0;
    for (int i = 0; i < parts; i++) {
        // 计算每个子列表的实际大小
        int currentSize = baseSize + (i < remainder ? 1 : 0); // 前 remainder 个子列表多一个元素
        List<T> sublist = new ArrayList<>();

        // 把当前子列表的元素放入
        for (int j = 0; j < currentSize; j++) {
            sublist.add(list.get(index++));
        }

        result.add(sublist);
    }

    return result;
}
[3] 取两个字段组成新对象
List<CarDTO> carDTOS = cars.stream().map (e -> new CarDTO(e.getCountry(), e.getName())).collect(Collectors.toList());         

redis

private SystemCleaningReportQueryResp queryCleanReportByTaskId(Long taskId) {
    String taskDate = taskId + "-" + DateUtil.format(new Date(), "yyyy-MM-dd");
    String key = formatTempRedisKey(taskDate);
    if (redisTemplate.opsForValue().get(key) != null) {
        log.warn("queryCleanReportByTaskId-key:{} queryByCate", key);
        return JacksonUtils.getJsonConvert().fromJsonString((String)redisTemplate.opsForValue().get(key),
            SystemCleaningReportQueryResp.class);
    } else {
        log.warn("queryCleanReportByTaskId-key:{} queryByInterface", key);
        SystemCleaningReportQueryResp systemCleaningReport = querySystemCleaningReport(taskId);
        redisTemplate.opsForValue().set(key, JacksonUtils.getJsonConvert().toJsonString(systemCleaningReport), 1,
            TimeUnit.DAYS);
        return systemCleaningReport;
    }
}

private String formatTempRedisKey(String tempId) {
    return String.format(TEMP_FILTER_REDIS_KEY, tempId);
}

private static final String TEMP_FILTER_REDIS_KEY = "clean:report:%s";