使用Java 8的流可以将该代码改写如下:

private Map<String, String> changeDict(Map<String, Object> map) { return map.entrySet().stream() .collect(Collectors.toMap(entry -> "${" + entry.getKey() + "}", entry -> { Object value = entry.getValue(); if (value instanceof LocalDateTime) { return ((LocalDateTime) value).format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")); } else if (value instanceof String) { String code = changeUtils.camel2under(entry.getKey()); List dictDataListByDictType = sysDictDataService.getDictDataListByDictType(code); if (dictDataListByDictType.isEmpty()) { return value.toString(); } return dictDataListByDictType.stream() .filter(dictDataDTO -> dictDataDTO.getDictValue().equals(value.toString())) .findFirst() .map(DictDataDTO::getDictLabel) .orElse(value.toString()); } else { return value.toString(); } }, (v1, v2) -> v2, HashMap::new)); }

此代码使用了Map的entrySet方法将Map转换为流,然后使用Collectors.toMap方法将流转换为Map。其中toMap方法的第一个参数为key的提取方式,使用entry.getKey();第二个参数为value的提取方式,使用一个Lambda表达式实现;第三个参数为当遇到重复key时的合并方式,这里使用v2代表后来的值覆盖前面的值;第四个参数为最终生成的Map类型,这里使用HashMap。

private MapString String changeDictMapString Object map HashMapString String changeMap = new HashMapString String; mapforEachk v - 默认取值为字符串类型 String value =

原文地址: https://www.cveoy.top/t/topic/brDu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录