Java工具类库大总结

1. Java自带工具方法

1.1 List集合拼接成以逗号分隔的字符串

// 如何把list集合拼接成以逗号分隔的字符串 a,b,c
List<String> list = Arrays.asList("a", "b", "c");
// 第一种方法,可以用stream流
String join = list.stream().collect(Collectors.joining(","));
System.out.println(join); // 输出 a,b,c
// 第二种方法,其实String也有join方法可以实现这个功能
String join = String.join(",", list);
System.out.println(join); 
// 输出 a,b,c

1.2 比较两个字符串是否相等,忽略大小写

/*
*当我们用equals比较两个对象是否相等的时候,还需要对左边的对象进行判空,不然可能会报空指针异常,
*我们可以用java.util包下Objects封装好的比较是否相等的方法
*/
System.out.println(Objects.equals(strA, strB));
// 输出结果:false

1.3 比较两个对象是否相等

//当我们用equals比较两个对象是否相等的时候,还需要对左边的对象进行判空,不然可能会报空指针异常,我们可以用java.util包下Objects封装好的比较是否相等的方法
String strA = "songwp";
String strB = "SONGWP";
if (strA.equalsIgnoreCase(strB)) {
     System.out.println("相等");
}
// 输出结果:相等
        
// 源码是这样的
public static boolean equals(Object a, Object b) { return (a == b) || (a != null && a.equals(b)); }

1.4 两个List集合取交集

List<String> list1 = new ArrayList<>();
        list1.add("a");
        list1.add("b");
        list1.add("c");
        List<String> list2 = new ArrayList<>();
        list2.add("a");
        list2.add("b");
        list2.add("d");
        list1.retainAll(list2);
        System.out.println(list1);
        // 输出结果:[a, b]

2. apache commons工具类库

apache commons是最强大的,也是使用最广泛的工具类库,里面的子库非常多,下面介绍几个最常用的

2.1 commons-lang,java.lang的增强版

建议使用commons-lang3,优化了一些api,原来的commons-lang已停止更新

Maven依赖是:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

2.1.1 字符串判空

传参CharSequence类型是String、StringBuilder、StringBuffer的父类,都可以直接下面方法判空,以下是源码:

public static boolean isEmpty(final CharSequence cs) {
    return cs == null || cs.length() == 0;
}
public static boolean isNotEmpty(final CharSequence cs) {
    return !isEmpty(cs);
}
// 判空的时候,会去除字符串中的空白字符,比如空格、换行、制表符
public static boolean isBlank(final CharSequence cs) {
    final int strLen = length(cs);
    if (strLen == 0) {
        return true;
    }
    for (int i = 0; i < strLen; i++) {
        if (!Character.isWhitespace(cs.charAt(i))) {
            return false;
        }
    }
    return true;
}
public static boolean isNotBlank(final CharSequence cs) {
    return !isBlank(cs);
}

2.1.2 首字母转成大写

String str = "yideng";
String capitalize = StringUtils.capitalize(str);
System.out.println(capitalize); // 输出Yideng

2.1.3 重复拼接字符串

String str = StringUtils.repeat("ab", 2);
System.out.println(str); // 输出abab

2.1.4 格式化日期

 // Date类型转String类型
String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
System.out.println("Date类型转String类型:"+date);
// 输出结果: Date类型转String类型:2023-06-06 15:16:13
// String类型转Date类型
Date date1 = DateUtils.parseDate("2021-05-01 01:01:01", "yyyy-MM-dd HH:mm:ss");
System.out.println("String类型转Date类型:"+date1);
// 输出结果:String类型转Date类型:Sat May 01 01:01:01 CST 2021
System.out.println("计算一年后的日期:"+DateUtils.addYears(new Date(), 1));
//输出结果:计算一年后的日期:Thu Jun 06 15:16:13 CST 2024
System.out.println("计算一个月后的日期:"+DateUtils.addMonths(new Date(), 1));
//输出结果:输出结果:计算一个月后的日期:Thu Jul 06 15:16:13 CST 2023
System.out.println("计算一天后的日期:"+DateUtils.addDays(new Date(), 1));
//输出结果:计算一天后的日期:Wed Jun 07 15:16:13 CST 2023
System.out.println("计算一周后的日期:"+DateUtils.addWeeks(new Date(), 1));
//输出结果:计算一周后的日期:Tue Jun 13 15:16:13 CST 2023
System.out.println("计算一个小时后的日期:"+DateUtils.addHours(new Date(), 1));
//输出结果:计算一个小时后的日期:Tue Jun 06 16:16:13 CST 2023
System.out.println("计算一秒后的日期:"+DateUtils.addSeconds(new Date(), 1));
//输出结果:计算一秒后的日期:Tue Jun 06 15:16:14 CST 2023
System.out.println("计算一分钟后的日期:"+DateUtils.addMinutes(new Date(), 1));
//输出结果:计算一分钟后的日期:Tue Jun 06 15:17:13 CST 2023
System.out.println("计算一毫秒后的日期:"+DateUtils.addMilliseconds(new Date(), 1));
//输出结果:计算一毫秒后的日期:Tue Jun 06 15:16:13 CST 2023

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依赖是:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

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<String> collection = CollectionUtils.retainAll(listA, listB);
// 两个集合取并集
Collection<String> collection = CollectionUtils.union(listA, listB);
// 两个集合取差集
Collection<String> collection = CollectionUtils.subtract(listA, listB);

2.3 common-beanutils 操作对象

Maven依赖:

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>
public class User {
    private Integer id;
    private String name;
}
设置对象属性

User user = new User();
BeanUtils.setProperty(user, "id", 1);
BeanUtils.setProperty(user, "name", "yideng");
System.out.println(BeanUtils.getProperty(user, "name")); // 输出 yideng
System.out.println(user); // 输出 {"id":1,"name":"yideng"}
对象和map互转

// 对象转map
Map<String, String> map = BeanUtils.describe(user);
System.out.println(map); // 输出 {"id":"1","name":"yideng"}
// map转对象
User newUser = new User();
BeanUtils.populate(newUser, map);
System.out.println(newUser); // 输出 {"id":1,"name":"yideng"}

2.4 commons-io 文件流处理

Maven依赖:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.8.0</version>
</dependency>
文件处理

File file = new File("demo1.txt");
// 读取文件
List<String> lines = FileUtils.readLines(file, Charset.defaultCharset());
// 写入文件
FileUtils.writeLines(new File("demo2.txt"), lines);
// 复制文件
FileUtils.copyFile(srcFile, destFile);

3. Google Guava 工具类库

Maven依赖:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>30.1.1-jre</version>
</dependency>

3.1 创建集合

List<String> list = Lists.newArrayList();
List<Integer> list = Lists.newArrayList(1, 2, 3);
// 反转list
List<Integer> reverse = Lists.reverse(list);
System.out.println(reverse); // 输出 [3, 2, 1]
// list集合元素太多,可以分成若干个集合,每个集合10个元素
List<List<Integer>> partition = Lists.partition(list, 10);
// 创建map和set
Map<String, String> map = Maps.newHashMap();
Set<String> set = Sets.newHashSet();

3.2 黑科技集合

3.2.1 Multimap 一个key可以映射多个value的HashMap

Multimap<String, Integer> map = ArrayListMultimap.create();
map.put("key", 1);
map.put("key", 2);
Collection<Integer> values = map.get("key");
System.out.println(map); // 输出 {"key":[1,2]}
// 还能返回你以前使用的臃肿的Map
Map<String, Collection<Integer>> collectionMap = map.asMap();
多省事,多简洁,省得你再创建 Map<String, List>

3.2.1 BiMap 一种连value也不能重复的HashMap

BiMap<String, String> biMap = HashBiMap.create();
// 如果value重复,put方法会抛异常,除非用forcePut方法
biMap.put("key","value");
System.out.println(biMap); // 输出 {"key":"value"}
// 既然value不能重复,何不实现个翻转key/value的方法,已经有了
BiMap<String, String> inverse = biMap.inverse();
System.out.println(inverse); // 输出 {"value":"key"}
这其实是双向映射,在某些场景还是很实用的。

3.2.3 Table 一种有两个key的HashMap

// 一批用户,同时按年龄和性别分组
Table<Integer, String, String> table = HashBasedTable.create();
table.put(18, "男", "yideng");
table.put(18, "女", "Lily");
System.out.println(table.get(18, "男")); // 输出 yideng
// 这其实是一个二维的Map,可以查看行数据
Map<String, String> row = table.row(18);
System.out.println(row); // 输出 {"男":"yideng","女":"Lily"}
// 查看列数据
Map<Integer, String> column = table.column("男");
System.out.println(column); // 输出 {18:"yideng"}

3.2.4 Multiset 一种用来计数的Set

Multiset<String> multiset = HashMultiset.create();
multiset.add("apple");
multiset.add("apple");
multiset.add("orange");
System.out.println(multiset.count("apple")); // 输出 2
// 查看去重的元素
Set<String> set = multiset.elementSet();
System.out.println(set); // 输出 ["orange","apple"]
// 还能查看没有去重的元素
Iterator<String> iterator = multiset.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}
// 还能手动设置某个元素出现的次数
multiset.setCount("apple", 5);

4.身份证工具类

提供身份证校验器,身份证信息获取方法,身份证号码脱敏方法

package com.utils;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;

/**
 * 身份证工具类
 * @author songwp
 * @create 2023/06/06
 */
public class CardUtil {
    private static final int[] COEFFICIENT_ARRAY = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};// 身份证校验码
    private static final String[] IDENTITY_MANTISSA = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};// 身份证号的尾数规则
    private static final String IDENTITY_PATTERN = "^[0-9]{17}[0-9Xx]$";
    /**
     * 身份证号码验证
     * 1、号码的结构
     * 公民身份号码是特征组合码,由十七位数字本体码和一位校验码组成。从左至右依次为:六位数字地址码,
     * 八位数字出生日期码,三位数字顺序码和一位数字校验码。
     * 2、地址码(前六位数)
     * 表示编码对象常住户口所在县(市、旗、区)的行政区划代码,按GB/T2260的规定执行。
     * 3、出生日期码(第七位至十四位)
     * 表示编码对象出生的年、月、日,按GB/T7408的规定执行,年、月、日代码之间不用分隔符。
     * 4、顺序码(第十五位至十七位)
     * 表示在同一地址码所标识的区域范围内,对同年、同月、同日出生的人编定的顺序号,
     * 顺序码的奇数分配给男性,偶数分配给女性。
     * 5、校验码(第十八位数)
     * (1)十七位数字本体码加权求和公式 S = Sum(Ai Wi), i = 0, , 16 ,先对前17位数字的权求和 ;
     * Ai:表示第i位置上的身份证号码数字值; Wi:表示第i位置上的加权因子 Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
     * (2)计算模 Y = mod(S, 11)
     * (3)通过模( 0 1 2 3 4 5 6 7 8 9 10)得到对应的校验码 Y:1 0 X 9 8 7 6 5 4 3 2
     */
    public static boolean isLegalPattern(String identity) {
        if (identity == null || identity.length() != 18 || !identity.matches(IDENTITY_PATTERN)) {
            return false;
        }
        char[] chars = identity.toCharArray();
        long sum = IntStream.range(0, 17).map(index -> {
            char ch = chars[index];
            int digit = Character.digit(ch, 10);
            int coefficient = COEFFICIENT_ARRAY[index];
            return digit * coefficient;
        }).summaryStatistics().getSum();
        // 计算出的尾数索引
        int mantissaIndex = (int) (sum % 11);
        String mantissa = IDENTITY_MANTISSA[mantissaIndex];
        String lastChar = identity.substring(17);
        return lastChar.equalsIgnoreCase(mantissa);
    }

    /**
     * 通过身份证号码获取 生日,年龄,性别代码
     * @param certificateNo 身份证号码
     * @return Map
     */
    public static Map<String, String> getBirthdayAgeSex(String certificateNo) {
        String birthday = "";
        String age = "";
        String sexCode = "";
        int year = Calendar.getInstance().get(Calendar.YEAR);
        char[] number = certificateNo.toCharArray();
        boolean flag = true;
        if (number.length == 15) {
            for (int x = 0; x < number.length; x++) {
                if (!flag) return new HashMap<String, String>();
                flag = Character.isDigit(number[x]);
            }
        } else if (number.length == 18) {
            for (int x = 0; x < number.length - 1; x++) {
                if (!flag) return new HashMap<String, String>();
                flag = Character.isDigit(number[x]);
            }
        }
        if (flag && certificateNo.length() == 15) {
            birthday = "19" + certificateNo.substring(6, 8) + "-"
                    + certificateNo.substring(8, 10) + "-"
                    + certificateNo.substring(10, 12);
            sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 3, certificateNo.length())) % 2 == 0 ? "F" : "M";
            age = (year - Integer.parseInt("19" + certificateNo.substring(6, 8))) + "";
        } else if (flag && certificateNo.length() == 18) {
            birthday = certificateNo.substring(6, 10) + "-"
                    + certificateNo.substring(10, 12) + "-"
                    + certificateNo.substring(12, 14);
            sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 4, certificateNo.length() - 1)) % 2 == 0 ? "F" : "M";
            age = (year - Integer.parseInt(certificateNo.substring(6, 10))) + "";
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("birthday", birthday);
        if(ValidateUtil.isEmpty(age)){
            map.put("age", "0");
        } else {
            map.put("age", age);
        }
        map.put("sexCode", sexCode);
        return map;
    }

    /**
     * 隐藏身份证某几位
     * @param idCard
     * @return String
     */
    public static String hideIdCard(String idCard){
        return idCard = idCard.replaceAll("(\\d{10})\\d{6}(\\d{2})","$1******$2");
    }
}

5.手机号码工具类

提供手机号码格式校验器,手机号码脱敏方法

package com.utils;

import org.apache.commons.lang3.StringUtils;
import java.util.regex.Pattern;

/**
 * 手机号码校验
 * @author songwp
 * @create 2023/06/06
 */
public class PhoneUtil {

    /**
     * 中国电信号码格式验证 手机段: 133,149,153,173,177,180,181,189,199,1349,1410,1700,1701,1702
     **/
    private static final String CHINA_TELECOM_PATTERN = "(?:^(?:\\+86)?1(?:33|49|53|7[37]|8[019]|99)\\d{8}$)|(?:^(?:\\+86)?1349\\d{7}$)|(?:^(?:\\+86)?1410\\d{7}$)|(?:^(?:\\+86)?170[0-2]\\d{7}$)";

    /**
     * 中国联通号码格式验证 手机段:130,131,132,145,146,155,156,166,171,175,176,185,186,1704,1707,1708,1709
     **/
    private static final String CHINA_UNICOM_PATTERN = "(?:^(?:\\+86)?1(?:3[0-2]|4[56]|5[56]|66|7[156]|8[56])\\d{8}$)|(?:^(?:\\+86)?170[47-9]\\d{7}$)";

    /**
     * 中国移动号码格式验证
     * 手机段:134,135,136,137,138,139,147,148,150,151,152,157,158,159,178,182,183,184,187,188,198,1440,1703,1705,1706
     **/
    private static final String CHINA_MOBILE_PATTERN = "(?:^(?:\\+86)?1(?:3[4-9]|4[78]|5[0-27-9]|78|8[2-478]|98)\\d{8}$)|(?:^(?:\\+86)?1440\\d{7}$)|(?:^(?:\\+86)?170[356]\\d{7}$)";

    /**
     * 中国大陆手机号码校验
     * @param phone
     * @return
     */
    public static boolean checkPhone(String phone) {
        if (StringUtils.isNotBlank(phone)) {
            if (checkChinaMobile(phone) || checkChinaUnicom(phone) || checkChinaTelecom(phone)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 中国移动手机号码校验
     * @param phone
     * @return
     */
    public static boolean checkChinaMobile(String phone) {
        if (StringUtils.isNotBlank(phone)) {
            Pattern regexp = Pattern.compile(CHINA_MOBILE_PATTERN);
            if (regexp.matcher(phone).matches()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 中国联通手机号码校验
     * @param phone
     * @return
     */
    public static boolean checkChinaUnicom(String phone) {
        if (StringUtils.isNotBlank(phone)) {
            Pattern regexp = Pattern.compile(CHINA_UNICOM_PATTERN);
            if (regexp.matcher(phone).matches()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 中国电信手机号码校验
     * @param phone
     * @return
     */
    public static boolean checkChinaTelecom(String phone) {
        if (StringUtils.isNotBlank(phone)) {
            Pattern regexp = Pattern.compile(CHINA_TELECOM_PATTERN);
            if (regexp.matcher(phone).matches()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 隐藏手机号中间四位
     * @param phone
     * @return String
     */
    public static String hideMiddleMobile(String phone) {
        if (StringUtils.isNotBlank(phone)) {
            phone = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        }
        return phone;
    }

    /*public static void main(String[] args) {
        log.debug(checkPhone("15600000001"));
        log.debug(hideMiddleMobile("15600000001"));
    }*/

}

6.中文拼音工具类

提供获取中文所有汉字首字母,中文首汉字首字母等方法

package com.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 中文拼音工具类
 * @author songwp
 * @create 2023/06/06
 */
public class PinyinUtil {

    /**
     * 获取第一个汉字的首字母
     * @param string
     * @return
     */
    public static String getPinYinFirstChar(String string) {
        if(ValidateUtil.isEmpty(string)){
            return "";
        }
        return getPinYinHeadChar(string).substring(0,1);
    }

    /**
     * 获取所有汉字首字母
     * @param string
     * @return
     */
    public static String getPinYinHeadChar(String string) {
        StringBuilder convert = new StringBuilder();
        for (int j = 0; j < string.length(); j++) {
            char word = string.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert.append(pinyinArray[0].charAt(0));
            } else {
                convert.append(word);
            }
        }
        return convert.toString().toUpperCase().substring(0,1);
    }

    /**
     * 获取汉字的所有大写拼音 eg:NANJINGSHI
     * @param name
     * @return
     * @throws BadHanyuPinyinOutputFormatCombination
     */
    public static String getAllUpperCaseChinese(String name) throws BadHanyuPinyinOutputFormatCombination {
        char[] charArray = name.toCharArray();
        StringBuilder pinyin = new StringBuilder();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);//设置大写格式
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//设置声调格式
        for(char c:charArray){
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {//匹配中文,非中文转换会转换成null
                String[] pinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(c,defaultFormat);
                pinyin.append(pinyinStringArray[0]);
            } else {
                pinyin.append(c);
            }
        }
        return pinyin.toString();
    }

    /**
     * 获取汉字的所有小写拼音 eg:nanjingshi
     * @param name
     * @return
     * @throws BadHanyuPinyinOutputFormatCombination
     */
    public static String getAllLowerCaseChinese(String name) throws BadHanyuPinyinOutputFormatCombination {
        char[] charArray = name.toCharArray();
        StringBuilder pinyin = new StringBuilder();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);//设置大写格式
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//设置声调格式
        for(char c:charArray){
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {//匹配中文,非中文转换会转换成null
                String[] pinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(c,defaultFormat);
                pinyin.append(pinyinStringArray[0]);
            } else {
                pinyin.append(c);
            }
        }
        return pinyin.toString();
    }

    /**
     * 获取汉字的所有首字母大写拼音 eg:NJS
     * @param name
     * @return
     * @throws BadHanyuPinyinOutputFormatCombination
     */
    public static String getUpperCaseChinese(String name) throws BadHanyuPinyinOutputFormatCombination {
        char[] charArray = name.toCharArray();
        StringBuilder pinyin = new StringBuilder();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);//设置大小写格式
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//设置声调格式
        for(char c:charArray){//匹配中文,非中文转换会转换成null
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                String[] hanyuPinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat);
                if (hanyuPinyinStringArray != null) {
                    pinyin.append(hanyuPinyinStringArray[0].charAt(0));
                }
            }
        }
        return pinyin.toString();
    }

    /**
     * 获取汉字的所有首字母小写拼音 eg:njs
     * @param name
     * @return
     * @throws BadHanyuPinyinOutputFormatCombination
     */
    public static String getLowerCaseChinese(String name) throws BadHanyuPinyinOutputFormatCombination {
        char[] charArray = name.toCharArray();
        StringBuilder pinyin = new StringBuilder();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);//设置大小写格式
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//设置声调格式
        for(char c:charArray){//匹配中文,非中文转换会转换成null
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                String[] hanyuPinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat);
                if (hanyuPinyinStringArray != null) {
                    pinyin.append(hanyuPinyinStringArray[0].charAt(0));
                }
            }
        }
        return pinyin.toString();
    }
}

7.时间工具类

提供时间,字符串转换.时间间隔计算,最大时间,最小时间等

package com.utils;

import com.chang.util.ValidateUtil;
import org.apache.commons.lang.time.DateFormatUtils;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间工具类
 * @author songwp
 * @create 2023/06/06
 */
public class DateUtil {

    public static String YEAR = "yyyy";
    public static String YEARMONTH = "yyyy-MM";
    public static String YEARMONTHDAY = "yyyy-MM-dd";
    public static String YEARMONTHDAYTIMEBRANCH = "yyyy-MM-dd HH:mm";
    public static String YEARMONTHDAYTIMEBRANCHSECOND = "yyyy-MM-dd HH:mm:ss";
    public static String YEARMONTHDAYTIMEBRANCHSECONDMILLISECOND = "yyyy-MM-dd HH:mm:ss SSS";
    private static long differDay = 1000 * 24 * 60 * 60;
    private static long differHour = 1000 * 60 * 60;
    private static long differMinute = 1000 * 60;
    private static long differSecond = 1000;
    public static String DIFFERTIME = "0分钟";

    /**
     * 获取当前时间戳 yyyy-MM-dd HH:mm:ss
     * @return String
     */
    public static String getCurrentTime(){
        return DateFormatUtils.format(new Date(),YEARMONTHDAYTIMEBRANCHSECOND);
    }

    /**
     * 获取年
     * @return String
     */
    public static String getYear(Date date){
        return DateFormatUtils.format(date,YEAR);
    }

    /**
     * 获取年月
     * @return String
     */
    public static String getYearMonth(Date date){
        return DateFormatUtils.format(date,YEARMONTH);
    }

    /**
     * 获取年月日
     * @return String
     */
    public static String getYearMonthDay(Date date){
        return DateFormatUtils.format(date,YEARMONTHDAY);
    }

    /**
     * 获取年月日
     * @return String
     */
    public static String getYearMonthDayForResult(Date date){
        return DateFormatUtils.format(date,"yyyy年MM月dd日");
    }

    /**
     * 获取年月日时分
     * @return String
     */
    public static String getYearMonthDayTimeBranch(Date date){
        return DateFormatUtils.format(date,YEARMONTHDAYTIMEBRANCH);
    }

    /**
     * 获取年月日时分秒
     * @return String
     */
    public static String getYearMonthDayTimeBranchSecond(Date date){
        return DateFormatUtils.format(date,YEARMONTHDAYTIMEBRANCHSECOND);
    }

    /**
     * 获取当月日时分秒毫秒
     * @return String
     */
    public static String getYearMonthDayTimeBranchSecondMillisecond(Date date){
        return DateFormatUtils.format(date,YEARMONTHDAYTIMEBRANCHSECONDMILLISECOND);
    }

    /**
     * 将时间转换成固定格式字符串
     * @param date 时间
     * @param pattern 时间格式
     * @return String
     */
    public static String getStringByDate(Date date,String pattern) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        LocalDateTime localDateTime = dateToDateTime(date);
        return formatter.format(localDateTime);
    }

    /**
     * 将字符串转换成固定格式时间 yyyy-MM-dd
     * @param string 时间字符串
     * @return Date
     */
    public static Date getDateByString(String string) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.parse(string, dateTimeFormatter);
        return localDateToDate(localDate);
    }

    /**
     * 将字符串转换成固定格式时间 yyyy-MM-dd HH:mm:ss
     * @param string 时间字符串
     * @return Date
     */
    public static Date getDateTimeByString(String string) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse(string, dateTimeFormatter);
        return dateTimeToDate(localDateTime);
    }

    /**
     * 获取某天最小时间
     * @param date 时间
     * @return Date
     */
    public static Date getDateMinTime(Date date) {
        LocalDateTime localDateTime = dateToDateTime(date);
        localDateTime = localDateTime.with(LocalTime.MIN);
        return dateTimeToDate(localDateTime);
    }

    /**
     * 获取某天最大时间
     * @param date 时间
     * @return Date
     */
    public static Date getDateMaxTime(Date date) {
        LocalDateTime localDateTime = dateToDateTime(date);
        localDateTime = localDateTime.with(LocalTime.MAX);
        return dateTimeToDate(localDateTime);
    }

    /**
     * 获取日期之后的某一天时间
     * @param date 时间
     * @param days 天数
     * @return Date
     */
    public static Date getAfterDaysDateTime(Date date, int days) {
        LocalDateTime localDateTime = dateToDateTime(date);
        localDateTime = localDateTime.plusDays(days);
        return dateTimeToDate(localDateTime);
    }

    /**
     * 获取日期之前的某一天时间
     * @param date 时间
     * @param days 天数
     * @return Date
     */
    public static Date getBeforeDaysDateTime(Date date, int days) {
        LocalDateTime localDateTime = dateToDateTime(date);
        localDateTime = localDateTime.minusDays(days);
        return dateTimeToDate(localDateTime);
    }

    /**
     * 获取日期月份第一天 00:00:00 000
     * @param date 时间
     * @return Date
     */
    public static Date getFirstDayOfMonth(Date date) {
        LocalDateTime localDateTime = dateToDateTime(date);
        localDateTime = localDateTime.with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN);
        return dateTimeToDate(localDateTime);
    }

    /**
     * 获取日期月份最后一天 23:59:59 999
     * @param date 时间
     * @return Date
     */
    public static Date getLastDayOfMonth(Date date) {
        LocalDateTime localDateTime = dateToDateTime(date);
        localDateTime = localDateTime.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX);
        return dateTimeToDate(localDateTime);
    }

    /**
     * 两个日期相差多少个月
     * @param dateBefore 开始时间
     * @param dateAfter 结束时间
     * @return Long
     */
    public static Long getUntilMonthByTwoDate(Date dateBefore, Date dateAfter) {
        LocalDate localDate1 = dateToLocalDate(dateBefore);
        LocalDate localDate2 = dateToLocalDate(dateAfter);
        return ChronoUnit.MONTHS.between(localDate1, localDate2);
    }

    /**
     * 两个日期相差多少天
     * @param dateBefore 开始时间
     * @param dateAfter 结束时间
     * @return Long
     */
    public static Long getUntilDayByTwoDate(Date dateBefore, Date dateAfter) {
        LocalDate localDate1 = dateToLocalDate(dateBefore);
        LocalDate localDate2 = dateToLocalDate(dateAfter);
        return ChronoUnit.DAYS.between(localDate1, localDate2);
    }

    /**
     * 两个日期相差多少小时
     * @param dateBefore 开始时间
     * @param dateAfter 结束时间
     * @return Long
     */
    public static Long getUntilHoursByTwoDate(Date dateBefore, Date dateAfter) {
        LocalDateTime localDate1 = dateToDateTime(dateBefore);
        LocalDateTime localDate2 = dateToDateTime(dateAfter);
        Long second = Duration.between(localDate1, localDate2).get(ChronoUnit.SECONDS);
        return second / 3600;
    }

    /**
     * 两个日期相差多少秒
     * @param dateBefore 开始时间
     * @param dateAfter 结束时间
     * @return Long
     */
    public static Long getUntilHoursByTwoSecond(Date dateBefore, Date dateAfter) {
        LocalDateTime localDate1 = dateToDateTime(dateBefore);
        LocalDateTime localDate2 = dateToDateTime(dateAfter);
        return Duration.between(localDate1, localDate2).get(ChronoUnit.SECONDS);
    }

    /**
     * LocalDateTime转换为Date
     * @param localDateTime 时间
     * @return Date
     */
    public static Date dateTimeToDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * Date转换为LocalDateTime
     * @param date 时间
     * @return LocalDateTime
     */
    public static LocalDateTime dateToDateTime(Date date) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }

    /**
     * Date转换为LocalDate
     * @param date 时间
     * @return LocalDate
     */
    public static LocalDate dateToLocalDate(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    /**
     * LocalDate转换为Date
     * @param localDate 时间
     * @return Date
     */
    public static Date localDateToDate(LocalDate localDate) {
        return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 获取增加天数后的日期
     * @param date 时间
     * @param days 天数
     * @return Date
     */
    public static Date getAddDay(Date date,Integer days){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, days);
        return calendar.getTime();
    }

    /**
     * 获取当前时间
     * @return Date
     */
    public static Date getCurDate() {
        return new Date();
    }

    /**
     * 获取两个时间相差时间
     * @param beforeDate 之前的时间
     * @param endDate 之后的时间
     * @return String
     */
    public static String getStringDateInfoByTwoDate(Date beforeDate,Date endDate) {
        long diff = endDate.getTime() - beforeDate.getTime();//获得两个时间的毫秒时间差异
        long day = diff / differDay;//计算差多少天
        long hour = diff % differDay / differHour;//计算差多少小时
        long min = diff % differDay % differHour / differMinute;//计算差多少分钟
        long second = diff % differDay % differHour % differMinute / differSecond;//计算差多少秒
        String string = "";
        if(0 != day){
            string = string + day + "天";
        }
        if(0 != hour){
            string = string + hour + "小时";
        }
        if(0 != min){
            string = string + min + "分钟";
        }
        if(ValidateUtil.isEmpty(string) && second > 0){//差距小于一分钟,计算秒
            string = second + "秒";
        }
        if(ValidateUtil.isEmpty(string)){//没有差距则为0分钟
            string = DIFFERTIME;
        }
        return string;
    }

    /**
     * 获取给定年月的最大最小日期
     * @param string yyyy-MM
     * @param flag true 最小日期 false 最大日期
     * @return String
     */
    public static String getMonthDayOneAndLast(String string,boolean flag){
        Integer year = Integer.parseInt(string.split("-")[0]);
        Integer month = Integer.parseInt(string.split("-")[1]);
        if(flag){
            return DateUtil.getDayByFlagOfMonth(year, month, true);
        }
        return DateUtil.getDayByFlagOfMonth(year, month, false);
    }

    /**
     * 获取给定年月的第一天和最后一天
     * @param year 年
     * @param month 月
     * @param flag true 第一天,false 最后一天
     * @return String
     */
    public static String getDayByFlagOfMonth(int year,int month,boolean flag){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);//设置年份
        calendar.set(Calendar.MONTH, month - 1);//设置月份
        if(flag){
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));//设置日历中月份的天数
        } else {
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));//设置日历中月份的天数
        }
        return getYearMonthDay(calendar.getTime());//格式化日期
    }

    /**
     * 计算传入时间是否超时
     * @param longDate 传入时间
     * @param intervalTime 规定时间 秒
     * @return boolean
     */
    public static boolean isTimeOut(Long longDate,Long intervalTime){
        return new Date(System.currentTimeMillis()).getTime() - new Date(longDate).getTime() / 1000 > intervalTime;
    }

}
posted @ 2023-06-06 15:53  奋--斗  阅读(56)  评论(0编辑  收藏  举报