java工具库类,减少开发代码量(一)

一、java集合工具

1.  两个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. List集合以特殊符号拼接为字符串

        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 join2 = String.join(",",list);
        System.out.println(join);   //输出a,b,c

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

        String strA = "Fan";
        String strB = "fan";
        if(strA.equalsIgnoreCase(strB))
            System.out.println("相等");

4. 比较两个对象是否相等

    public static void main(String[] args) {
        //当我们用equals比较两个对象是否相等的时候,还需要对左边的对象进行判空,
        // 不然可能会报空指针异常,我们可以用java.util包下Objects封装好的比较是否相等的方法
        String strA = null;
        String strB = "fan";
        Objects.equals(strA,strB);
    }
    // 源码实现
    public static boolean equals(Object a, Object b) {
        return (a == b) || (a != null && a.equals(b));
    }

二、apache commons 工具类库

apache commons是最强大的,也是使用最广泛的工具类库,里面的子库非常多,下面介绍几个最常用的,有兴趣的同学可以自己去看看源码。

commons-lang,java.lang的增强版

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

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 int length(CharSequence cs) {
        return cs == null ? 0 : cs.length();
    }
    public static boolean isNotBlank(final CharSequence cs){
        return !isBlank(cs);
    }

2. 首字母转成大写

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

3. 重复拼接字符串

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

4. 格式化日期

        // 不需要手写SimpleDateFormat格式化了
        // Date类型转String类型
        String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        System.out.println(date);

        // String类型转Date类型
        Date date1 = DateUtils.parseDate("2022-12-07 20:01:01", "yyyy-MM-dd HH:mm:ss");
        System.out.println(date1);

        // 计算一个小时后的日期
        Date date2 = DateUtils.addHours(new Date(), 1);
        System.out.println(date2);

5. 包装临时对象

        // 当一个方法需要返回两个及以上字段时,我们一般会封装成一个临时对象返回,现在有了 Pair和 Triple就不需要了
        // 返回两个字段
        ImmutablePair<Integer, String> pair = ImmutablePair.of(1, "fan");
        System.out.println(pair.getLeft() + "," + pair.getRight()); // 输出 1,yideng  
        // 返回三个字段
        ImmutableTriple<Integer, String, Date> triple = ImmutableTriple.of(1, "fan", new Date());
        System.out.println(triple.getLeft() + "," + triple.getMiddle() + "," + triple.getRight());

三、commons-collections 集合工具类

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

1. 集合判空

import org.apache.commons.collections4.CollectionUtils;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class javaAPITest {
    public static void main(String[] args) throws ParseException {
        List<String> listA= new ArrayList<>();
        listA.add("a");
        listA.add("b");
        listA.add("c");
        List<String> listB = new ArrayList<>();
        listB.add("a");
        listB.add("b");
        listB.add("d");
        // 两个集合取交集
        Collection<String> collection1 = CollectionUtils.retainAll(listA, listB);
        // 两个集合取并集
        Collection<String> collection2 = CollectionUtils.union(listA, listB);
        // 两个集合取差集
        Collection<String> collection3 = CollectionUtils.subtract(listA, listB);
    }
    // 封装了集合判空的方法
    public static boolean isEmpty(final Collection<?> coll) {
    return coll == null || coll.isEmpty();  
    }  
              
    public static boolean isNotEmpty(final Collection<?> coll) {  
    return !isEmpty(coll);  
    }

}

 四、common-beanutils 操作对象

        <dependency>  
                <groupId>commons-beanutils</groupId>  
                <artifactId>commons-beanutils</artifactId>  
                <version>1.9.4</version>  
        </dependency>  

1. 修改对象属性

        User user = new User();
        BeanUtils.setProperty(user, "age", 18);
        BeanUtils.setProperty(user, "name", "fan");
        // 使用 BeanUtils 获取属性值
        System.out.println(BeanUtils.getProperty(user, "name"));
        System.out.println(user);
        // 对象转map
        Map<String, String> map = BeanUtils.describe(user);
        System.out.println("对象转map:"+map);
        // map转对象
        User newUser = new User();
        BeanUtils.populate(newUser, map);
        System.out.println("map转对象:"+newUser);

结果:

fan
User(name=fan, sex=null, age=18)
对象转map:{sex=null, name=fan, age=18}
map转对象:User(name=fan, sex=null, age=18)

五、commons-io 文件流处理

        <dependency>  
                <groupId>commons-io</groupId>  
                <artifactId>commons-io</artifactId>  
                <version>2.8.0</version>  
        </dependency>

1. 文件流操作 

对文件进行读取、写入、复制操作。

        String srcFile = "D:\\a.txt";
        String destFile = "D:\\KuGou\\b.txt";
        // 文件处理
        File sfile = new File(srcFile);
        File dfile = new File(destFile);
        File cfile = new File("E:\\c.txt");
        // 读取文件
        List<String> lines = FileUtils.readLines(sfile, Charset.defaultCharset());
        // 写入文件
        FileUtils.writeLines(dfile, lines);
        // 复制文件
        FileUtils.copyFile(sfile, cfile);

六、Google Guava 工具类库

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

1. 创建集合

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

2. 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);
        // 还能返回合集Map<String, List>
        Map<String, Collection<Integer>> collectionMap = map.asMap();
        collectionMap.forEach((key,value) ->System.out.println(key+"---"+value));
{key=[1, 2]}
key---[1, 2]

3. 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"}
{key=value}
{value=key}

4. Table

一种有两个key的HashMap,很有意思哈

    // 一批用户,同时按年龄和性别分组
        Table<Integer, String, String> table = HashBasedTable.create();  
        table.put(18, "男", "zhangsan");
        table.put(18, "女", "lisi");
        // 再次添加会覆盖
        table.put(18, "女", "qianqian");
        table.put(19, "男", "haha");
        table.put(19, "女", "wangwu");
        System.out.println(table.get(18, "女"));
        /**
         *  这其实是一个二维的Map
         *          男         女
         *  18  zhangsan      qianqian
         *  19    haha        wangwu
         */
        // 查看行数据
        Map<String, String> row = table.row(18);
        System.out.println(row);
        // 查看列数据
        Map<Integer, String> column = table.column("男");  
        System.out.println(column);
qianqian
{男=zhangsan, 女=qianqian}
{18=zhangsan, 19=haha}

5. 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);
        System.out.println(multiset.count("apple")); // 输出 5
2
[orange, apple]
orange
apple
apple
5

6. Preconditions.checkNotNull()

优雅的判断空对象

    Objects object = null;
        Preconditions.checkNotNull(object,  "空指针异常,对象信息:"+object);
Exception in thread "main" java.lang.NullPointerException: 空指针异常,对象信息:null
	at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:899)
	at com.fan.esjavaapi.api.javaAPITest.main(javaAPITest.java:17)

源码:

    @CanIgnoreReturnValue
    public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) {
        if (reference == null) {
            throw new NullPointerException(String.valueOf(errorMessage));
        } else {
            return reference;
        }
    }

源码很简单, @Nullable注解,该注解没有实际作用,主要是提示编译器或开发人员,被它修饰的对象可能为空。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值