代码整洁之道

他强由他强,清风拂山岗,

他横由他横,明月照大江,

他自狠来他自恶,

我自一口真气足

1 github地址

博客里为了阅读,删除了大量注释,完整代码请前往github查看

https://github.com/xiaoma55/code-concise

2 空值判断

2.1 null值抛异常

1
2
3
4
5
6
7
8
9
10
11
# 优化前

if (null == x) {
// throw new NullPointerException();
throw new NullPointerException("参数为null");
}

# 优化后

Objects.requireNonNull(x);
Objects.requireNonNull(x, "参数为null");

3 String

3.1 字符串拼接

1
2
3
4
5
6
7
8
9
# 优化前
String test = name + " " + age + " " + param;

# 优化后
String test = new StringJoiner(" ")
.add(name)
.add(age)
.add(param)
.toString();

3.2 字符串占位符

有时候我们经常需要一些变量有前缀之类的,可以像下面这样

1
2
3
4
5
6
7
8
9
// 原生java
String home = "我是{0}的,{1}{2}的,{3}{4}的,{5}话是这样说";
home = MessageFormat.format(home, "中国", "中国", "庆阳", "庆阳", "宁县", "宁县");
System.out.println(home);

// hutool方式
String home1 = "我是{}的,{}{}的,{}{}的,{}话是这样说";
home1 = StrUtil.format(home1, "中国", "中国", "重庆", "重庆", "涪陵", "涪陵");
System.out.println(home1);

4 Enum

4.1 枚举通用方法

以前对枚举的操作,比如获取values等,需要在每个枚举类中写方法。今天规整一下,让所有枚举默认有一些通用方法

4.1.1 定义一个接口

1
2
3
4
5
6
public interface INameValueEnum<T> {
String getKey();
T getValue();
Integer getSort();
String getDescription();
}

1.1.2 操作工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class EnumUtils {

public static <E extends INameValueEnum<V>, V, T> V getValueByKey(Class<E> enumClass, String key) {
return Arrays.stream(enumClass.getEnumConstants()).filter(e -> e.getKey().equals(key)).findFirst().map(INameValueEnum::getValue).orElse(null);
}

public static <E extends INameValueEnum<V>, V, T> String getKeyByValue(Class<E> enumClass, T value) {
return Arrays.stream(enumClass.getEnumConstants()).filter(e -> e.getValue().equals(value)).findFirst().map(INameValueEnum::getKey).orElse(null);
}

public static <E extends INameValueEnum<V>, V> List<String> getKeys(Class<E> enumClass) {
return Arrays.stream(enumClass.getEnumConstants()).map(INameValueEnum::getKey).collect(Collectors.toList());
}

public static <E extends INameValueEnum<V>, V> List<V> getValues(Class<E> enumClass) {
return Arrays.stream(enumClass.getEnumConstants()).map(INameValueEnum::getValue).collect(Collectors.toList());
}

public static <E extends INameValueEnum<V>, V> List<E> getEnumsBySort(Class<E> enumClass) {
return Arrays.stream(enumClass.getEnumConstants()).sorted(Comparator.comparingInt(e -> e.getSort() == null ? 0 : e.getSort())).collect(Collectors.toList());
}

public static <E extends INameValueEnum<V>, V> List<String> getKeysBySort(Class<E> enumClass) {
return Arrays.stream(enumClass.getEnumConstants()).sorted(Comparator.comparingInt(e -> e.getSort() == null ? 0 : e.getSort())).map(INameValueEnum::getKey).collect(Collectors.toList());
}

public static <E extends INameValueEnum<V>, V> List<V> getValuesBySort(Class<E> enumClass) {
return Arrays.stream(enumClass.getEnumConstants()).sorted(Comparator.comparingInt(e -> e.getSort() == null ? 0 : e.getSort())).map(INameValueEnum::getValue).collect(Collectors.toList());
}

public static <E extends INameValueEnum<V>, V> E getEnumByValue(Class<E> enumClass, V value) {
return Arrays.stream(enumClass.getEnumConstants()).filter(e -> e.getValue().equals(value)).findFirst().orElse(null);
}

public static <E extends INameValueEnum<V>, V> E getEnumByKey(Class<E> enumClass, String key) {
return Arrays.stream(enumClass.getEnumConstants()).filter(e -> e.getKey().equals(key)).findFirst().orElse(null);
}

public static <E extends INameValueEnum<V>, V> boolean isExistValue(Class<E> enumClass, V value) {
return Arrays.stream(enumClass.getEnumConstants()).anyMatch(e -> e.getValue().equals(value));
}

public static <E extends INameValueEnum<V>, V> boolean isExistKey(Class<E> enumClass, String name) {
return Arrays.stream(enumClass.getEnumConstants()).anyMatch(e -> e.getKey().equals(name));
}
}

4.1.3 定义枚举

这里定义两个枚举用于测试

1
2
3
4
5
6
7
8
9
10
11
12
13
@Getter
@AllArgsConstructor
public enum ProgramLanguageEnum implements INameValueEnum<String> {

/** 编程语言 */
GOLANG("GO_LANG", "GoLang", "是 Google 的 Robert Griesemer,Rob Pike 及 Ken Thompson 开发的一种静态强类型、编译型语言。", 1),
JAVASCRIPT("JAVA_SCRIPT", "JavaScript", "是一种具有函数优先的轻量级,解释型或即时编译型的编程语言。", 2);

private final String key;
private final String value;
private final String description;
private final Integer sort;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Getter
@AllArgsConstructor
public enum LolKillEnum implements INameValueEnum<Integer> {

/** LOL击杀集锦 */
FIRSTBLOOD("FIRST_BLOOD", 1, "第一滴血", 1),
DOUBLEKILL("DOUBLE_KILL", 2, "双杀", 2),
TRIPLEKILL("TRIPLE_KILL", 3, "三杀", 3),
QUADRKILL("QUADR_KILL", 4, "四杀", 4),
PEATAKILL("PEATA_KILL", 5, "五杀", 5);

private final String key;
private final Integer value;
private final String description;
private final Integer sort;
}

4.1.4 测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.ma.concise.enumutil;

import com.ma.concise.enumutil.enums.LolKillEnum;
import com.ma.concise.enumutil.enums.ProgramLanguageEnum;
import com.ma.concise.enumutil.util.EnumUtils;
import org.junit.jupiter.api.Test;


public class EnumTest {
@Test
public void isExist(){
System.out.println(EnumUtils.isExistValue(LolKillEnum.class,1));
System.out.println(EnumUtils.isExistValue(LolKillEnum.class,2));
System.out.println(EnumUtils.isExistValue(ProgramLanguageEnum.class,"GoLang"));
System.out.println(EnumUtils.isExistValue(ProgramLanguageEnum.class,"JavaScript"));
System.out.println(EnumUtils.isExistKey(ProgramLanguageEnum.class,"GO_LANG"));
System.out.println(EnumUtils.isExistKey(ProgramLanguageEnum.class,"JAVA_SCRIPT"));

}
@Test
public void getKeyByValue(){
System.out.println(EnumUtils.getKeyByValue(LolKillEnum.values(),1));
System.out.println(EnumUtils.getKeyByValue(ProgramLanguageEnum.values(),null));
}
@Test
public void getValueByKey(){
System.out.println(EnumUtils.getValueByKey(LolKillEnum.values(),"FIRST_BLOOD"));
System.out.println(EnumUtils.getValueByKey(ProgramLanguageEnum.values(),"GO_LANG"));
}
@Test
public void getEnumByValue(){
System.out.println(EnumUtils.getEnumByValue(LolKillEnum.class,1));
System.out.println(EnumUtils.getEnumByValue(ProgramLanguageEnum.class,"JavaScript"));
}

@Test
public void getEnumByKey(){
System.out.println(EnumUtils.getEnumByKey(LolKillEnum.class,"DOUBLE_KILL"));
System.out.println(EnumUtils.getEnumByKey(ProgramLanguageEnum.class,"JAVA_SCRIPT"));
}

@Test
public void getKeys(){
System.out.println(EnumUtils.getKeys(LolKillEnum.class));
}

@Test
public void getValues(){
System.out.println(EnumUtils.getValues(LolKillEnum.class));
}

@Test
public void getSort(){
System.out.println(EnumUtils.getEnumsBySort(LolKillEnum.class));
System.out.println(EnumUtils.getKeysBySort(LolKillEnum.class));
System.out.println(EnumUtils.getValuesBySort(LolKillEnum.class));
}
}

5 Time

5.1 常用时间相关方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.experimental.UtilityClass;
import org.springframework.util.StringUtils;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;

/**
* @Description: 时间工具类
* @Package: com.hex.ds.source.common.util
* @ClassName: TimeUtils
*
* @Author: xiaoma
* @Date: 2022/1/11 20:47
* @Version: v1.0
**/
@UtilityClass
public class TimeUtils {
/* 全局时区设置,系统默认时区 ZoneId.systemDefault(),指定时区 ZoneId.of("America/St_Johns") */
public final ZoneId defaultZoneId = ZoneId.systemDefault();
/* 默认格式化格式,所有返回格式化字符串的方法,如果传了null或者空串,则使用这个 */
public final String defaultPattern = "yyyy-MM-dd HH:mm:ss";

public final int ONE_MILLISECOND = 1;
public final int ONE_SECOND_MILLISECOND = 1000 * ONE_MILLISECOND;
public final int ONE_MINUTE_MILLISECOND = 60 * ONE_SECOND_MILLISECOND;
public final int ONE_HOUR_MILLISECOND = 60 * ONE_MINUTE_MILLISECOND;
public final int ONE_DAY_MILLISECOND = 24 * ONE_HOUR_MILLISECOND;
public final String[] EN_MONTH = new String[]{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
public final String[] ZH_MONTH = new String[]{"一月份", "二月份", "三月份", "四月份", "五月份", "六月份", "七月份", "八月份", "九月份", "十月份", "十一月份", "十二月份"};
public final String[] EN_WEEK = new String[]{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
public final String[] ZH_WEEK = new String[]{"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
public final String[] ZH_WEEK_ABBREVIATION = new String[]{"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
public final String ZH = "ZH", EN = "EN";

public int getCurrentTimeYear() {
return LocalDateTime.now().atZone(defaultZoneId).getYear();
}

public int getCurrentTimeMonth() {
return LocalDateTime.now().atZone(defaultZoneId).getMonthValue();
}

public int getCurrentTimeWeek() {
return LocalDateTime.now().atZone(defaultZoneId).getDayOfWeek().getValue();
}

public int getCurrentTimeDay() {
return LocalDateTime.now().atZone(defaultZoneId).getDayOfMonth();
}

public int getCurrentTimeHour() {
return LocalDateTime.now().atZone(defaultZoneId).getHour();
}

public int getCurrentTimeMinute() {
return LocalDateTime.now().atZone(defaultZoneId).getMinute();
}

public int getCurrentTimeSecond() {
return LocalDateTime.now().atZone(defaultZoneId).getSecond();
}

public long getCurrentTimeMillis() {
return System.currentTimeMillis();
}

public long getCurrentTimePlusTime(long millis) {
return System.currentTimeMillis() + millis;
}

public long getCurrentTimePlusTime(int year, int month, int day, int hour, int minute, int second) {
return LocalDateTime.now().atZone(defaultZoneId).plusYears(year).plusMonths(month).plusDays(day).plusHours(hour).plusMinutes(minute).plusSeconds(second).toInstant().toEpochMilli();
}

public String getCurrentTimeFormat(String pattern) {
return LocalDateTime.now().atZone(defaultZoneId).format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

public String getCurrentTimePlusTimeFormat(long millis, String pattern) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis() + millis), defaultZoneId).format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

public String getCurrentTimePlusTimeFormat(int year, int month, int day, int hour, int minute, int second, String pattern) {
return LocalDateTime.now().atZone(defaultZoneId).plusYears(year).plusMonths(month).plusDays(day).plusHours(hour).plusMinutes(minute).plusSeconds(second).format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

/* ************************************************************************************************************************ */

public int getTargetTimeYear(long timeMillis) {
return Integer.valueOf(LocalDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), defaultZoneId).format(DateTimeFormatter.ofPattern("yyyy")));
}

public int getTargetTimeMonth(long timeMillis) {
return Integer.valueOf(LocalDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), defaultZoneId).format(DateTimeFormatter.ofPattern("MM")));
}

public int getTargetTimeWeek(long timeMillis) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), defaultZoneId).getDayOfWeek().getValue();
}

public int getTargetTimeWeek(int year, int month, int day, int hour, int minute, int second) {
return LocalDateTime.of(year, month, day, hour, minute, second).atZone(defaultZoneId).getDayOfWeek().getValue();
}

public int getTargetTimeDay(long timeMillis) {
return Integer.valueOf(LocalDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), defaultZoneId).format(DateTimeFormatter.ofPattern("dd")));
}

public int getTargetTimeHour(long timeMillis) {
return Integer.valueOf(LocalDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), defaultZoneId).format(DateTimeFormatter.ofPattern("HH")));
}

public int getTargetTimeMinute(long timeMillis) {
return Integer.valueOf(LocalDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), defaultZoneId).format(DateTimeFormatter.ofPattern("mm")));
}

public int getTargetTimeSecond(long timeMillis) {
return Integer.valueOf(LocalDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), defaultZoneId).format(DateTimeFormatter.ofPattern("ss")));
}

public long getTargetTimeMillis(int year, int month, int day, int hour, int minute, int second) {
return LocalDateTime.of(year, month, day, hour, minute, second).atZone(defaultZoneId).toInstant().toEpochMilli();
}

public long getTargetTimePlusTime(int year, int month, int day, int hour, int minute, int second, long millis) {
return LocalDateTime.of(year, month, day, hour, minute, second).atZone(defaultZoneId).toInstant().toEpochMilli() + millis;
}

public long getTargetTimePlusTime(int year, int month, int day, int hour, int minute, int second, int plusYear, int plusMonth, int plusDay, int plusHour, int plusMinute, int plusSecond) {
return LocalDateTime.of(year, month, day, hour, minute, second).atZone(defaultZoneId).toInstant().toEpochMilli() +
LocalDateTime.of(plusYear, plusMonth, plusDay, plusHour, plusMinute, plusSecond).atZone(defaultZoneId).toInstant().toEpochMilli();
}

public String getTargetTimeFormat(long timeMillis, String pattern) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), defaultZoneId).format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

public String getTargetTimePlusTimeFormat(long timeMillis, long timeMillisPlus, String pattern) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(timeMillis + timeMillisPlus), defaultZoneId).format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

public String getTargetTimePlusTimeFormat(long timeMillis, int year, int month, int day, int hour, int minute, int second, String pattern) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(
LocalDateTime.of(year, month, day, hour, minute, second).atZone(defaultZoneId).toInstant().toEpochMilli() + timeMillis), defaultZoneId).
format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

public String getTargetTimeFormat(int year, int month, int day, int hour, int minute, int second, String pattern) {
return LocalDateTime.of(year, month, day, hour, minute, second).format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

public String getTargetTimePlusTimeFormat(int year, int month, int day, int hour, int minute, int second, long timeMillis, String pattern) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(
LocalDateTime.of(year, month, day, hour, minute, second).atZone(defaultZoneId).toInstant().toEpochMilli() + timeMillis), defaultZoneId).
format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

public String getTargetTimePlusTimeFormat(int year, int month, int day, int hour, int minute, int second, int plusYear, int plusMonth, int plusDay, int plusHour, int plusMinute, int plusSecond, String pattern) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(
LocalDateTime.of(year, month, day, hour, minute, second).atZone(defaultZoneId).toInstant().toEpochMilli() +
LocalDateTime.of(plusYear, plusMonth, plusDay, plusHour, plusMinute, plusSecond).atZone(defaultZoneId).toInstant().toEpochMilli()), defaultZoneId).
format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

/* ************************************************************************************************************************ */

public long getFirstDayOfYear() {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.firstDayOfYear()).withHour(0).withMinute(0).withSecond(0).withNano(0).toInstant().toEpochMilli();
}

public long getLastDayOfYear() {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.lastDayOfYear()).withHour(0).withMinute(0).withSecond(0).withNano(0).toInstant().toEpochMilli();
}

public long getFirstDayOfMonth() {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0).withNano(0).toInstant().toEpochMilli();
}

public long getLastDayOfMonth() {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.lastDayOfMonth()).withHour(0).withMinute(0).withSecond(0).withNano(0).toInstant().toEpochMilli();
}

public long getFirstDayWeekInMonth(int week) {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.firstInMonth(DayOfWeek.of(week))).withHour(0).withMinute(0).withSecond(0).withNano(0).toInstant().toEpochMilli();
}

public long getLastDayWeekInMonth(int week) {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.lastInMonth(DayOfWeek.of(week))).withHour(0).withMinute(0).withSecond(0).withNano(0).toInstant().toEpochMilli();
}

public long getNextDayWeek(int week) {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.next(DayOfWeek.of(week))).withHour(0).withMinute(0).withSecond(0).withNano(0).toInstant().toEpochMilli();
}

public long getNextOrSameDayWeek(int week) {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.nextOrSame(DayOfWeek.of(week))).withHour(0).withMinute(0).withSecond(0).withNano(0).toInstant().toEpochMilli();
}

public long getPreviousDayWeek(int week) {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.previous(DayOfWeek.of(week))).withHour(0).withMinute(0).withSecond(0).withNano(0).toInstant().toEpochMilli();
}

public long getPreviousOrSameDayWeek(int week) {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.previousOrSame(DayOfWeek.of(week))).withHour(0).withMinute(0).withSecond(0).withNano(0).toInstant().toEpochMilli();
}

public String getFirstDayOfYear(String pattern) {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.firstDayOfYear()).withHour(0).withMinute(0).withSecond(0).withNano(0).format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

public String getLastDayOfYear(String pattern) {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.lastDayOfYear()).withHour(0).withMinute(0).withSecond(0).withNano(0).format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

public String getFirstDayOfMonth(String pattern) {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0).withNano(0).format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

public String getLastDayOfMonth(String pattern) {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.lastDayOfMonth()).withHour(0).withMinute(0).withSecond(0).withNano(0).format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

public String getFirstDayWeekInMonth(int week, String pattern) {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.firstInMonth(DayOfWeek.of(week))).withHour(0).withMinute(0).withSecond(0).withNano(0).format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

public String getLastDayWeekInMonth(int week, String pattern) {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.lastInMonth(DayOfWeek.of(week))).withHour(0).withMinute(0).withSecond(0).withNano(0).format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

public String getNextDayWeek(int week, String pattern) {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.next(DayOfWeek.of(week))).withHour(0).withMinute(0).withSecond(0).withNano(0).format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

public String getNextOrSameDayWeek(int week, String pattern) {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.nextOrSame(DayOfWeek.of(week))).withHour(0).withMinute(0).withSecond(0).withNano(0).format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

public String getPreviousDayWeek(int week, String pattern) {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.previous(DayOfWeek.of(week))).withHour(0).withMinute(0).withSecond(0).withNano(0).format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

public String getPreviousOrSameDayWeek(int week, String pattern) {
return LocalDateTime.now().atZone(defaultZoneId).with(TemporalAdjusters.previousOrSame(DayOfWeek.of(week))).withHour(0).withMinute(0).withSecond(0).withNano(0).format(DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? defaultPattern : pattern));
}

public DurationTime getDurationTimeSeparate(int year, int month, int day, int hour, int minute, int second) {
ZonedDateTime zonedDateTimeNow = LocalDateTime.now().atZone(defaultZoneId);
ZonedDateTime zonedDateTimeTarget = LocalDateTime.of(year, month, day, hour, minute, second).atZone(defaultZoneId);
return getDurationTimeSeparate(zonedDateTimeNow, zonedDateTimeTarget);
}

public DurationTime getDurationTimeSeparate(long timeMillis) {
ZonedDateTime zonedDateTimeNow = LocalDateTime.now().atZone(defaultZoneId);
ZonedDateTime zonedDateTimeTarget = LocalDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), defaultZoneId).atZone(defaultZoneId);
return getDurationTimeSeparate(zonedDateTimeNow, zonedDateTimeTarget);
}

public DurationTime getDurationTimeSeparate(ZonedDateTime zonedDateTimeNow, ZonedDateTime zonedDateTimeTarget) {
long years = ChronoUnit.YEARS.between(zonedDateTimeNow, zonedDateTimeTarget);
long months = ChronoUnit.MONTHS.between(zonedDateTimeNow, zonedDateTimeTarget);
long days = ChronoUnit.DAYS.between(zonedDateTimeNow, zonedDateTimeTarget);
long hours = ChronoUnit.HOURS.between(zonedDateTimeNow, zonedDateTimeTarget);
long minutes = ChronoUnit.MINUTES.between(zonedDateTimeNow, zonedDateTimeTarget);
long seconds = ChronoUnit.SECONDS.between(zonedDateTimeNow, zonedDateTimeTarget);
long millis = ChronoUnit.MILLIS.between(zonedDateTimeNow, zonedDateTimeTarget);
return new DurationTime(years, months, days, hours, minutes, seconds, millis);
}

public DurationTime getDurationTimeUnSeparate(int year, int month, int day, int hour, int minute, int second) {
LocalDate localDateNow = LocalDate.now(defaultZoneId);
LocalDate localDateTarget = LocalDate.now(defaultZoneId).withYear(year).withMonth(month).withDayOfMonth(day);
Period p = Period.between(localDateNow, localDateTarget);
ZonedDateTime zonedDateTimeNow = LocalDateTime.now().atZone(defaultZoneId);
ZonedDateTime zonedDateTimeTarget = LocalDateTime.of(year, month, day, hour, minute, second).atZone(defaultZoneId);
Duration between = Duration.between(zonedDateTimeNow, zonedDateTimeTarget);
return getDurationTimeUnSeparate(p, between);
}

public DurationTime getDurationTimeUnSeparate(long timeMillis) {
LocalDate localDateNow = LocalDate.now(defaultZoneId);
LocalDate localDateTarget = LocalDate.now(defaultZoneId).withYear(getTargetTimeYear(timeMillis)).withMonth(getTargetTimeMonth(timeMillis)).withDayOfMonth(getTargetTimeDay(timeMillis));
Period p = Period.between(localDateNow, localDateTarget);
ZonedDateTime zonedDateTimeNow = LocalDateTime.now().atZone(defaultZoneId);
ZonedDateTime zonedDateTimeTarget = LocalDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), defaultZoneId).atZone(defaultZoneId);
Duration between = Duration.between(zonedDateTimeNow, zonedDateTimeTarget);
return getDurationTimeUnSeparate(p, between);
}

public DurationTime getDurationTimeUnSeparate(Period p, Duration between) {
int years = p.getYears();
int months = p.getMonths();
int days = p.getDays();
long hours = between.toHours() % 24;
long minutes = between.toMinutes() % 60;
long seconds = between.getSeconds() % 60;
long millis = between.toMillis() % 1000;
return new DurationTime(years, months, days, hours, minutes, seconds, millis);
}

/* ************************************************************************************************************************* */

public String getMonthByNumber(String targetType, int month, boolean abbreviation, boolean lowerCase) {
if (ZH.equals(targetType) || ZH.toLowerCase().equals(targetType)) {
if (!abbreviation) {
return ZH_MONTH[month - 1];
}
return ZH_MONTH[month - 1].substring(0, ZH_MONTH[month - 1].length() - 1);
} else if (EN.equals(targetType) || EN.toLowerCase().equals(targetType)) {
if (!abbreviation) {
return !lowerCase ? EN_MONTH[month - 1] : EN_MONTH[month - 1].toLowerCase();
}
return !lowerCase ? EN_MONTH[month - 1].substring(0, 3) : EN_MONTH[month - 1].toLowerCase().substring(0, 3);
}
return "";
}

public int getNumberByMonth(String month) {
for (int i = 0, j = 12; i < j; i++) {
if (month.equals(ZH_MONTH[i]) ||
month.equals(ZH_MONTH[i].substring(0, ZH_MONTH[i].length() - 1)) ||
month.equals(ZH_MONTH[i].substring(0, ZH_MONTH[i].length() - 2)) ||
month.equals(EN_MONTH[i]) ||
month.equals(EN_MONTH[i].toLowerCase()) ||
month.equals(EN_MONTH[i].substring(0, 3)) ||
month.equals(EN_MONTH[i].substring(0, 3).toLowerCase())) {
return i + 1;
}
}
return 0;
}

public String getWeekByNumber(String targetType, int week, boolean abbreviation, boolean lowerCase) {
if (ZH.equals(targetType) || ZH.toLowerCase().equals(targetType)) {
if (!abbreviation) {
return ZH_WEEK[week - 1];
}
return ZH_WEEK_ABBREVIATION[week - 1];
} else if (EN.equals(targetType) || EN.toLowerCase().equals(targetType)) {
if (!abbreviation) {
return !lowerCase ? EN_WEEK[week - 1] : EN_WEEK[week - 1].toLowerCase();
}
return !lowerCase ? EN_WEEK[week - 1].substring(0, 3) : EN_WEEK[week - 1].toLowerCase().substring(0, 3);
}
return "";
}

public int getNumberByWeek(String week) {
for (int i = 0, j = 7; i < j; i++) {
if (week.equals(ZH_WEEK[i]) ||
week.equals(ZH_WEEK[i].substring(ZH_WEEK[i].length() - 1)) ||
week.equals(ZH_WEEK_ABBREVIATION[i]) ||
week.equals(EN_WEEK[i]) ||
week.equals(EN_WEEK[i].toLowerCase()) ||
week.equals(EN_WEEK[i].substring(0, 3)) ||
week.equals(EN_WEEK[i].substring(0, 3).toLowerCase())) {
return i + 1;
}
}
return 0;
}

@Data
@AllArgsConstructor
public class DurationTime {
private long year;
private long month;
private long day;
private long hour;
private long minute;
private long seconds;
private long millis;
}
}

6 map

6.1 过滤指定的key

过滤出有效的key或者过滤掉无效的key

注意,这个类里用到了前面写的enumUtil

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class MapUtils {

public static <K, V, T> Map<K, V> filterValidKeys(Map<K, V> map, List<T> validKeys) {
return map.entrySet().stream().filter(entry -> validKeys.contains(entry.getKey())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}

public static <K, V, T> List<Map<K, V>> filterValidKeys(List<Map<K, V>> list, List<T> validKeys) {
return list.stream().map(e -> filterValidKeys(e, validKeys)).collect(Collectors.toList());
}

public static <K, V, E extends INameValueEnum<T>, T> Map<K, V> filterValidKeys(Map<K, V> map, Class<E> enumClass) {
return map.entrySet().stream().filter(entry -> EnumUtils.getValues(enumClass).contains(entry.getKey())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}

public static <K, V, E extends INameValueEnum<T>, T> List<Map<K, V>> filterValidKeys(List<Map<K, V>> list, Class<E> enumClass) {
return list.stream().map(e -> filterValidKeys(e, enumClass)).collect(Collectors.toList());
}

public static <K, V, T> Map<K, V> filterUnValidKeys(Map<K, V> map, List<T> validKeys) {
return map.entrySet().stream().filter(entry -> !validKeys.contains(entry.getKey())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}

public static <K, V, T> List<Map<K, V>> filterUnValidKeys(List<Map<K, V>> list, List<T> validKeys) {
return list.stream().map(e -> filterUnValidKeys(e, validKeys)).collect(Collectors.toList());
}

public static <K, V, E extends INameValueEnum<T>, T> Map<K, V> filterUnValidKeys(Map<K, V> map, Class<E> enumClass) {
return map.entrySet().stream().filter(entry -> !EnumUtils.getValues(enumClass).contains(entry.getKey())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}

public static <K, V, E extends INameValueEnum<T>, T> List<Map<K, V>> filterUnValidKeys(List<Map<K, V>> list, Class<E> enumClass) {
return list.stream().map(e -> filterUnValidKeys(e, enumClass)).collect(Collectors.toList());
}

public static <K, V> List<V> filterOneColumnValues(List<Map<K, V>> list, String columnName) {
return list.stream().map(t -> t.get(columnName)).collect(Collectors.toList());
}
}

Finally 躺板板

红伞伞白杆杆,吃完一起躺板板

躺板板埋山山,亲朋都来吃饭饭

饭饭里有红伞伞,吃完全村埋山山,来年长满红伞伞

联系博主,加入【羊山丨交流社区】

联系博主


本博客所有文章除特别声明外,均为原创。版权归博主小马所有。任何团体、机构、媒体、网站、公众号及个人不得转载。如需转载,请联系博主(关于页面)。如其他团体、机构、媒体、网站、博客或个人未经博主允许擅自转载使用,请自负版权等法律责任!