首页 > 编程语言 >Java常用第三方工具类

Java常用第三方工具类

时间:2023-06-10 12:32:22浏览次数:48  
标签:常用 Java String System StringUtils println import 第三方 out

一、Apache StringUtils:专为Java字符串而生的工具类

添加依赖:

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

1.字符串判空

isEmpty: 判断null、""

isNotEmpty:判断null、""

isBlank:判断null、""、" "

isNotBlank:判断null、""、" "

示例代码如下:

import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
 
/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: StringUtils测试
 */
@SpringBootTest
public class StringTest {
 
    @Test
    void test1() {
        String str1 = null;
        String str2 = "";
        String str3 = " ";
        String str4 = "abc";
        String str5 = "null";
 
        System.out.println(StringUtils.isEmpty(str1));
        System.out.println(StringUtils.isEmpty(str2));
        System.out.println(StringUtils.isEmpty(str3));
        System.out.println(StringUtils.isEmpty(str4));
        System.out.println(StringUtils.isEmpty(str5));
 
        System.out.println("=====");
        System.out.println(StringUtils.isNotEmpty(str1));
        System.out.println(StringUtils.isNotEmpty(str2));
        System.out.println(StringUtils.isNotEmpty(str3));
        System.out.println(StringUtils.isNotEmpty(str4));
        System.out.println(StringUtils.isNotEmpty(str5));
 
        System.out.println("=====");
        System.out.println(StringUtils.isBlank(str1));
        System.out.println(StringUtils.isBlank(str2));
        System.out.println(StringUtils.isBlank(str3));
        System.out.println(StringUtils.isBlank(str4));
        System.out.println(StringUtils.isBlank(str5));
 
        System.out.println("=====");
        System.out.println(StringUtils.isNotBlank(str1));
        System.out.println(StringUtils.isNotBlank(str2));
        System.out.println(StringUtils.isNotBlank(str3));
        System.out.println(StringUtils.isNotBlank(str4));
        System.out.println(StringUtils.isNotBlank(str5));
    }
}

执行结果:

true
true
false
false
false
=====
false
false
true
true
true
=====
true
true
true
false
false
=====
false
false
false
true
true

2.分割字符串

使用StringUtils的split()方法分割字符串成数组。

示例代码如下:

import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
 
import java.util.Arrays;
 
/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: StringUtils测试
 */
@SpringBootTest
public class StringTest {
 
    @Test
    void test1() {
        String result = "a,b,c";
        String[] arr = StringUtils.split(result, ",");
        // 输出[a, b, c]
        System.out.println(Arrays.toString(arr));
    }
}

3.判断是否纯数字

使用StringUtils的isNumeric()方法判断字符串是否是纯数字形式。

示例代码如下:

import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
 
 
/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: StringUtils测试
 */
@SpringBootTest
public class StringTest {
 
    @Test
    void test1() {
        String data1 = "2";
        // 输出true
        System.out.println(StringUtils.isNumeric(data1));
        String data2 = "hello";
        // 输出false
        System.out.println(StringUtils.isNumeric(data2));
    }
}

4.将集合拼接成字符串

使用StringUtils的join(集合,"需要拼接的字符")方法将集合的数据拼接成字符串。

示例代码如下:

import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
 
import java.util.ArrayList;
import java.util.List;
 
 
/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: StringUtils测试
 */
@SpringBootTest
public class StringTest {
 
    @Test
    void test1() {
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        // 输出a,b,c
        System.out.println(StringUtils.join(list, ","));
    }
}

5.其他方法

trim(String str):去除字符串首尾的空白字符。

trimToEmpty(String str):去除字符串首尾的空白字符,如果字符串为 null,则返回空字符串。

trimToNull(String str):去除字符串首尾的空白字符,如果结果为空字符串,则返回 null。

equals(String str1, String str2):比较两个字符串是否相等。

equalsIgnoreCase(String str1, String str2):比较两个字符串是否相等,忽略大小写。

startsWith(String str, String prefix):检查字符串是否以指定的前缀开头。

endsWith(String str, String suffix):检查字符串是否以指定的后缀结尾。

contains(String str, CharSequence seq):检查字符串是否包含指定的字符序列。

indexOf(String str, CharSequence seq):返回指定字符序列在字符串中首次出现的索引,如果没有找到,则返回 -1。

lastIndexOf(String str, CharSequence seq):返回指定字符序列在字符串中最后一次出现的索引,如果没有找到,则返回 -1。

substring(String str, int start, int end):截取字符串中指定范围的子串。

replace(String str, String searchString, String replacement):替换字符串中所有出现的搜索字符串为指定的替换字符串。

replaceAll(String str, String regex, String replacement):使用正则表达式替换字符串中所有匹配的部分。

join(Iterable<?> iterable, String separator):使用指定的分隔符将可迭代对象中的元素连接为一个字符串。

split(String str, String separator):使用指定的分隔符将字符串分割为一个字符串数组。

capitalize(String str):将字符串的第一个字符转换为大写。

uncapitalize(String str):将字符串的第一个字符转换为小写。


二、Hutool工具包

添加依赖:

<!--hutool-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.12</version>
</dependency>

1.类型转换

我们接收客户端传过来的数据的时候,通常我们需要把这些数据转换成我们需要的数据类型。

示例代码如下:

import cn.hutool.core.convert.Convert;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
 
/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: hutool测试
 */
@SpringBootTest
public class HutoolTest {
 
    @Test
    void test1() {
        String param = null;
        // 输出null
        System.out.println(Convert.toInt(param));
        // 设置了默认值 输出0
        System.out.println(Convert.toInt(param, 0));
        
        // 输出Fri Jun 09 00:00:00 CST 2023
        System.out.println(Convert.toDate("2023年06月09日"));
    }
}

2.日期时间转换

我们使用DateUtil来格式化日期

示例代码如下:

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
 
import java.util.Date;
 
/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: hutool测试
 */
@SpringBootTest
public class HutoolTest {
 
    @Test
    void test1() {
        // 输出2023-06-09 09:55:24
        System.out.println(DateUtil.date());
        // 输出2023-06-09 00:00:00
        DateTime dateTime = DateUtil.parse("2023-06-09");
        System.out.println(dateTime);
 
        // 输出2023-06-09
        Date date = new Date();
        System.out.println(DateUtil.formatDate(date));
    }
}

3.反射工具

Hutool 封装的反射工具 ReflectUtil 包括:

  • 获取构造方法
  • 获取字段
  • 获取字段值
  • 获取方法
  • 执行方法(对象方法和静态方法)

示例代码如下:

import cn.hutool.core.util.ReflectUtil;
 
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
 
/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: ReflectUtil测试
 */
public class ReflectTest {
    private int id;
 
    public ReflectTest() {
        System.out.println("构造方法");
    }
 
    public void show() {
        System.out.println("普通方法");
    }
 
 
    public static void main(String[] args) throws IllegalAccessException {
        // 获取对象
        ReflectTest reflectTest = ReflectUtil.newInstance(ReflectTest.class);
        reflectTest.show();
 
        // 构造方法
        Constructor[] constructors = ReflectUtil.getConstructors(ReflectTest.class);
        for (Constructor constructor : constructors) {
            System.out.println(constructor.getName());
        }
 
        // 获取字段
        Field field = ReflectUtil.getField(ReflectTest.class, "id");
        field.setInt(reflectTest, 20);
        // 输出20
        System.out.println(ReflectUtil.getFieldValue(reflectTest, field));
 
        Method[] methods = ReflectUtil.getMethods(ReflectTest.class);
        for (Method method : methods) {
            System.out.println(method.getName());
        }
        // 获取指定方法
        Method method = ReflectUtil.getMethod(ReflectTest.class, "show");
        System.out.println(method.getName());
 
        // 执行方法 输出普通方法
        ReflectUtil.invoke(reflectTest, "show");
 
    }
}

4.身份证工具

使用IdcardUtil的isValidCard验证身份证是否合法。

示例代码如下:

import cn.hutool.core.util.IdcardUtil;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
 
 
/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: hutool测试
 */
@SpringBootTest
public class HutoolTest {
 
    @Test
    void test1() {
        // 输出false
        System.out.println(IdcardUtil.isValidCard("43243"));
    }
}

5.字段验证器

验证客户端传过来的数据,比如手机号码、邮箱、IP地址等是否合法。

示例代码如下:

import cn.hutool.core.lang.Validator;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
 
 
/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: hutool测试
 */
@SpringBootTest
public class HutoolTest {
 
    @Test
    void test1() {
        String email = "[email protected]";
        // 输出true
        System.out.println(Validator.isEmail(email));
 
        String mobile = "1887888";
        // 输出false
        System.out.println(Validator.isMobile(mobile));
 
        String ip = "192.168";
        // 输出false
        System.out.println(Validator.isIpv4(ip));
    }
}

6.缓存工具

CacheUtil 是 Hutool 封装的创建缓存的快捷工具类,可以创建不同的缓存对象:

FIFOCache:先入先出,元素不停的加入缓存直到缓存满为止,当缓存满时,清理过期缓存对象,清理后依旧满则删除先入的缓存。

LFUCache,最少使用,根据使用次数来判定对象是否被持续缓存,当缓存满时清理过期对象,清理后依旧满的情况下清除最少访问的对象并将其他对象的访问数减去这个最少访问数,以便新对象进入后可以公平计数。

LRUCache,最近最久未使用,根据使用时间来判定对象是否被持续缓存,当对象被访问时放入缓存,当缓存满了,最久未被使用的对象将被移除。

示例代码如下:

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
 
 
/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: hutool测试
 */
@SpringBootTest
public class HutoolTest {
 
    @Test
    void test1() {
        Cache<String, String> fifoCache = CacheUtil.newFIFOCache(3);
        fifoCache.put("key1", "a");
        fifoCache.put("key2", "b");
        fifoCache.put("key3", "c");
        fifoCache.put("key4", "d");
 
        // 缓存大小为 3,所以 key4 放入后 key1 被清除 输出null
        System.out.println(fifoCache.get("key1"));
        // 输出b
        System.out.println(fifoCache.get("key2"));
 
 
        Cache<String, String> lfuCache = CacheUtil.newLFUCache(3);
        lfuCache.put("key1", "a");
        // 使用次数+1
        lfuCache.get("key1");
        lfuCache.put("key2", "b");
        lfuCache.put("key3", "c");
        lfuCache.put("key4", "d");
        // 由于缓存容量只有 3,当加入第 4 个元素的时候,最少使用的将被移除(2,3被移除)
        // 都是输出null
        System.out.println(lfuCache.get("key2"));
        System.out.println(lfuCache.get("key3"));
 
 
        Cache<String, String> lruCache = CacheUtil.newLRUCache(3);
        lruCache.put("key1", "a");
        lruCache.put("key2", "b");
        lruCache.put("key3", "c");
        // 使用时间近了
        lruCache.get("key1");
        lruCache.put("key4", "d");
 
        // 由于缓存容量只有 3,当加入第 4 个元素的时候,最久使用的将被移除(2)
        String value2 = lruCache.get("key2");
        // 输出null
        System.out.println(value2);
    }
}

三、Guava:Google开源的Java工具库 

添加依赖:

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

1.字符串处理

示例代码如下:

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
 
import java.util.Optional;
 
/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: Guava测试
 */
@SpringBootTest
public class GuavaTest {
 
    @Test
    void test() {
        // 1.字符串拼接
        Joiner joiner = Joiner.on(",");
        // 输出hello,world,qq
        System.out.println(joiner.join("hello", "world", "qq"));
 
        // 2.字符串拆分
        String data = "hello,world,qq";
        // 输出[hello, world, qq]
        System.out.println(Splitter.on(",").splitToList(data));
    }
}

2.集合工具

示例代码如下:

import com.google.common.collect.Lists;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
 
/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: Guava测试
 */
@SpringBootTest
public class GuavaTest {
 
    @Test
    void test() {
        // 创建空集合
        List<Integer> emptyList = Lists.newArrayList();
        // 初始化集合
        List<Integer> initList = Lists.newArrayList(1, 2, 3);
 
        // 输出[]
        System.out.println(emptyList);
        // 输出[1, 2, 3]
        System.out.println(initList);
    }
}

标签:常用,Java,String,System,StringUtils,println,import,第三方,out
From: https://blog.51cto.com/u_13312531/6454435

相关文章

  • 5.信号处理(1) --常用信号平滑去噪的方法
    ✅作者简介:热爱科研的算法开发者,Python、Matlab项目可交流、沟通、学习。......
  • 【数学荟萃】第10期:考研数学常用泰勒公式汇总
    泰勒公式是考研数学中同学必须掌握的一系列公式,在求极限、解答题的中值定理问题上面大有用武之地。但是它的公式太多太杂,为了方便学生学习,下面总结了这些公式。为了方便排版,这里直接发图片。由于比较匆忙,如存在小错误请批评指正。 需要pdf文件的同学,扫描下面二维码关注公众号【......
  • Ubuntu常用软件安装
    前言最近,犹豫和纠结之后,又决定把ubuntu当做日常主要的系统来使用了,于是又开始新一轮折腾ubuntu的相关配置,一个算是给自己积累点知识库,另一个也算是提想尝试的小伙伴踩个坑,好了,废话少说,让我们直接开始吧。常用软件安装ubuntu系统的软件安装方式,一种是在线安装,也就是通过包管理命......
  • Java 配置环境(保姆式教学)
    第一步:下载JDK(1)下载JDK(下载地址:oracle.com/java)(2-1)JDK 17(LTS)    //受长期技术支持更新 在JDK21 LTS还没出来之前是最新的受长期技术支持更新的JDK下载后的样子:.exe.zip下载以后就是一个压缩包解压以后就是这样,我的jdk-17是重命名以后的 (2-2)JDK8(LTS)//大学一般使用J......
  • JS中循环遍历数组的几种常用方式总结
    第一种:for循环,也是最常见的最简单的一种,也是使用频率最高的一种,虽然性能不弱,但仍有优化空间constarr=[11,22,33,44,55,66,77,88];for(leti=0;i<arr.length;i++){console.log(arr[i]);}第二种:优化版for循环constarr=[11,22,33,44,5......
  • 常用DOS命令
    CMD命令打开CMD的方式: 开始+系统+命令提示符Win+R弹出运行框输入CMD在任意的文件夹下按住shift键+鼠标右键点击找到powershell(与命令提示符一样)在资源文件中地址栏前面加上cmd+空格管理员打开方式:(可获得最高权限)开始+系统+命令提示符右键选择管理员打开......
  • Java 命名规范
    包命名规范包(Package)的作用是将功能相似或相关的类或者接口进行分组管理,便于类的定位和查找,同时也可以使用包来避免类名的冲突和访问控制,使代码更容易维护。通常,包名使用小写英文字母进行命名,并使用“.”进行分割,每个被分割的单元只能包含一个名词。一般地,包命名常采用顶......
  • JAVA的springboot+vue家政服务管理平台,家政预约管理系统,附源码+数据库+论文+PPT
    1、项目介绍随着家政服务行业的不断发展,家政服务在现实生活中的使用和普及,家政服务行业成为近年内出现的一个新行业,并且能够成为大众广为认可和接受的行为和选择。设计家政服务管理平台的目的就是借助计算机让复杂的销售操作变简单,变高效。家政服务管理平台采用了B/S结构,JAVA作......
  • JAVA——包装类及Integer的成员方法
    JAVA——包装类及Integer的成员方法用一个对象,把基本类型给包起来基本数据类型对应的对象byte->Byteshort->Shortchar->Characterint->Integerlong->Longfloat->Floatdouble->Doubleboolean->Boolean细节:因为在实际开发中,-128-127之间的数据,用的比较......
  • Arthas常用的命令(二)--trace
    trace参数参数名称参数说明class-pattern类名表达式匹配method-pattern方法名表达式匹配condition-express条件表达式-E开启正则表达式匹配,默认为通配符匹配-n命令执行次数#cost方法执行耗时-m指定Class最大匹配数量,默认值为50。trace......