1.DateTimeFormatter对当前日期进行格式化,并提取出年、月、日的字符串表示。

1
2
3
4
5
6
7
8
9
10
11
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");

// 获取当前日期并格式化为 "yyyyMMdd" 格式的字符串
String day = LocalDate.now().format(dtf); // 输出例如 "20240628"

// 提取出前六位字符作为月份,格式为 "yyyyMM"
String month = day.substring(0, 6); // 输出例如 "202406"

// 提取出前四位字符作为年份,格式为 "yyyy"
String year = day.substring(0, 4); // 输出例如 "2024"

2.通常用于将集合的数据根据某个字段进行分类累加 eg:如下根据废料集合的marker来进行计算重量并整合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
List<Map<String, Object>> mapList = new ArrayList<>();
List<String> markerList = new ArrayList<>();

for (IntoWarehouse intoWarehouse : wasteList) {
if (markerList.contains(intoWarehouse.getMarker())) {
for (Map<String, Object> map : mapList) {
if (map.get("marker").equals(intoWarehouse.getMarker())) {
BigDecimal weight = intoWarehouse.getWeight().add(new BigDecimal(map.get("weight").toString()));
map.put("weight", weight);
}
}
} else {
markerList.add(intoWarehouse.getMarker());
Map<String, Object> map = new HashMap<>();
map.put("marker", intoWarehouse.getMarker());
map.put("weight", intoWarehouse.getWeight());
mapList.add(map);
}
}