2.1.3 重复拼接字符串
String str = StringUtils.repeat(“ab”, 2);
System.out.println(str); // 输出abab
2.1.4 格式化日期
再也不用手写SimpleDateFormat格式化了
// Date类型转String类型
String date = DateFormatUtils.format(new Date(), “yyyy-MM-dd HH:mm:ss”);
System.out.println(date); // 输出 2021-05-01 01:01:01
// String类型转Date类型
Date date = DateUtils.parseDate(“2021-05-01 01:01:01”, “yyyy-MM-dd HH:mm:ss”);
// 计算一个小时后的日期
Date date = DateUtils.addHours(new Date(), 1);
2.1.5 包装临时对象
当一个方法需要返回两个及以上字段时,我们一般会封装成一个临时对象返回,现在有了Pair和Triple就不需要了
// 返回两个字段
ImmutablePair<Integer, String> pair = ImmutablePair.of(1, “yideng”);
System.out.println(pair.getLeft() + “,” + pair.getRight()); // 输出 1,yideng
// 返回三个字段
ImmutableTriple<Integer, String, Date> triple = ImmutableTriple.of(1, “yideng”, new Date());
System.out.println(triple.getLeft() + “,” + triple.getMiddle() + “,” + triple.getRight()); // 输出 1,yideng,Wed Apr 07 23:30:00 CST 2021
2.2 commons-collections 集合工具类
Maven依赖是:
org.apache.commons
commons-collections4
4.4
2.2.1 集合判空
封装了集合判空的方法,以下是源码:
public static boolean isEmpty(final Collection<?> coll) {
return coll == null || coll.isEmpty();
}
public static boolean isNotEmpty(final Collection<?> coll) {
return !isEmpty(coll);
}
// 两个集合取交集
Collection collection = CollectionUtils.