【Code】Java高频代码备忘录
Java
# Map
根据key排序
Map<String, String> sortMap = new TreeMap<>((String s1, String s2) -> s1.compareTo(s2));
sortMap.putAll(map);
1
2
2
快速构建Map
private Map<Integer, String> newsEventMap = new HashMap<Integer, String>(){{
put(k1, "v1");
put(k2, "v2");
}};
1
2
3
4
2
3
4
获取第一个元素
map.entrySet().stream().findFirst();
1
# List
交换两个元素位置
Collections.swap(list, 0, 6);
1
按数量分批
// guava
Lists.partition(list, 500);// 每500个分为1组
// apache common collection
ListUtils.partition(list, 500);
1
2
3
4
2
3
4
排序
// 升序
list.sort(Comparator.comparing(Xxx::getXxx));
// 降序
list.sort(Comparator.comparing(Xxx::getXxx).reversed());
1
2
3
4
2
3
4
分组后排序
// null在前,其它倒排
list.stream().collect(Collectors.groupingBy(
Xxx::getXxx,
Collectors.collectingAndThen(Collectors.toList(),
o -> o.stream().sorted(Comparator.comparing(Xxx::getYyy)).collect(Collectors.toList())))
);
1
2
3
4
5
6
2
3
4
5
6
// null在前,其它倒排
list.stream().sorted(Comparator.comparing(Xxx::getXxx,
Comparator.nullsLast(Xxx::compareTo)).reversed()).collect(Collectors.toList());
1
2
3
2
3
按汉字首字母排序
List<String> list = Arrays.asList(
new String[]{"中山","汕头","广州","安庆","阳江","南京","武汉","北京","安阳","北方"}
);
list = list.stream()
.sorted(Collator.getInstance(Locale.CHINA))
.collect(Collectors.toList());
1
2
3
4
5
6
2
3
4
5
6
public class Main {
public static void main(String[] args) {
List<Address> list = Arrays.asList(new Address[]{new Address("中山"), new Address("汕头"), new Address("广州")});
list = list.stream().sorted(Comparator.comparing(o->Collator.getInstance(Locale.CHINA).getCollationKey(o.getName()))).collect(Collectors.toList());
}
@Data
@AllArgsConstructor
@NoArgsConstructor
private static class Address {
public String name;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
转Map
// guava
Maps.uniqueIndex(list, Object::getKey);// key objecct
1
2
2
collectors.toMap()值为空导致空指针解决方法
Map<Integer, Boolean> collect = list.stream()
.collect(HashMap::new, (m,v)-> m.put(v.getId(), v.getAnswer()), HashMap::putAll);
1
2
2
按属性统计数量(校验重复数量)
Map<String, Long> map = list.stream().map(Xxx::getXxx).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
1
# JSON
Gson转换指定泛型类型
List<Object> list = new Gson().fromJson("{}", new TypeToken<List<Object>>() {}.getType());
1
ObjectMap转换指定泛型类型
Map<String, String> json = new ObjectMapper().readValue("{}", new TypeReference<Map<String, String>>() {});
1
详情见:https://www.baeldung.com/java-super-type-tokens (opens new window)
# String
编码转换
new String("string".getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8)
1
# 日期时间
获取当天的开始时间和结束时间
LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天开始
LocalDateTime todayEnd = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);//当天结束
1
2
2
获取当年的开始时间和结束时间
Date startDate = Date.from(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()).atStartOfDay(ZoneId.systemDefault()).toInstant());
Date endDate = Date.from(LocalDate.now().with(TemporalAdjusters.lastDayOfYear()).atTime(LocalTime.MAX).atZone(ZoneId.systemDefault()).toInstant());
1
2
2
获取当前时间到第二天的时间差
public final class DateUtils {
private DateUtils() {
}
/**
* 获取当前时间直到当天结束的时间差
*
* @param currentTime
* @param unit
* @return
*/
public static Long getUntilTomorrowTime(Date currentTime, ChronoUnit unit) {
//从一个 Instant和区域ID获得 LocalDateTime实例
LocalDateTime localDateTime = LocalDateTime.ofInstant(currentTime.toInstant(), ZoneId.systemDefault());
//获取第第二天零点时刻的实例
LocalDateTime toromorrowTime = LocalDateTime.ofInstant(currentTime.toInstant(), ZoneId.systemDefault())
.plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
//ChronoUnit日期枚举类, between方法计算两个时间对象之间的时间量
return unit.between(localDateTime, toromorrowTime);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
DateUtils.getUntilTomorrowTime(new Date(), ChronoUnit.SECONDS)
1