zoukankan      html  css  js  c++  java
  • Java程序员必会的工具库,代码量减少90%

    作者 | 一灯架构

    来源 | www.toutiao.com/i6943239541448917512

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

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

    if (strA.equalsIgnoreCase(strB)) {
        System.out.println("相等");
    }

    1.3 比较两个对象是否相等

      当我们用equals比较两个对象是否相等的时候,还需要对左边的对象进行判空,不然可能会报空指针异常,我们可以用java.util包下Objects封装好的比较是否相等的方法

    Objects.equals(strA, strB);

      源码是这样的

    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 字符串判空

      StringUtils工具类,传参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 格式化日期

      再也不用手写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依赖是:

    <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);
    }

    2.2.2 集合交集、并集、差集

    // 两个集合取交集
    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 创建集合

    // 创建ArrayList
    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); // 创建HashMap Map<String, String> map = Maps.newHashMap(); // 创建HashSet Set<String> set = Sets.newHashSet();

    3.2 黑科技集合

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

      多省事,多简洁,省得你再创建 Map<String, List<Integer>>

    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();

    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. hutool 工具类库

      Maven依赖:

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

      这是一个很符合国人操作系统的工具类库,提供很多有用的工具类

    4.1 Convert 转换

     //数字转大写
    double a = 123456.01;
    System.out.println(Convert.digitToChinese(a));
    //输出: 壹拾贰万叁仟肆佰伍拾陆元零壹分
    
    //转换为字符串
    int i = 1;
    String aStr = Convert.toStr(a);
    //转换为指定类型数组
    String[] b = {"1", "2", "3", "4"};
    Integer[] bArr = Convert.toIntArray(b);
    //转换为日期对象
    String dateStr = "2017-05-06";
    Date date = Convert.toDate(dateStr);
    System.out.println("转换为日期对象: "+date);
    //转换为列表
    String[] strArr = {"a", "b", "c", "d"};
    List<String> strList = Convert.toList(String.class, strArr);
    System.out.println("转换为列表: "+strList);

    4.2 DateUtil: 日期时间工具类 

    //Date、long、Calendar之间的相互转换
    //当前时间
    Date date = DateUtil.date();
    //Calendar转Date
    date = DateUtil.date(Calendar.getInstance());
    //时间戳转Date
    date = DateUtil.date(System.currentTimeMillis());
    //自动识别格式转换
    String dateStr = "2017-03-01";
    date = DateUtil.parse(dateStr);
    //自定义格式化转换
    date = DateUtil.parse(dateStr, "yyyy-MM-dd");
    //格式化输出日期
    String format = DateUtil.format(date, "yyyy-MM-dd");
    //获得年的部分
    int year = DateUtil.year(date);
    //获得月份,从0开始计数  +1获取当前月份
    int month = DateUtil.month(date);
    //获取某天的开始2020-09-01 00:00:00、结束时间 2020-09-01 23:59:59
    Date beginOfDay = DateUtil.beginOfDay(date);
    Date endOfDay = DateUtil.endOfDay(date);
    //计算偏移后的日期时间 (当前时间加两天)
    Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
    //计算日期时间之间的偏移量(date与newDate相差的天数)
    long betweenDay = DateUtil.between(date, newDate, DateUnit.DAY);

    4.3 StrUtil:字符串工具类

    //判断是否为空字符串
    String str = "test";
    StrUtil.isEmpty(str);
    StrUtil.isNotEmpty(str);
    //去除字符串的前后缀
    StrUtil.removeSuffix("a.jpg", ".jpg");
    StrUtil.removePrefix("a.jpg", "a.");
    //格式化字符串    这只是个占位符:我是占位符
    String template = "这只是个占位符:{}";
    String str2 = StrUtil.format(template, "我是占位符");
    LOGGER.info("/strUtil format:{}", str2);

    4.4 ClassPathResource 获取classPath下的文件

      在Tomcat等容器下,classPath一般是WEB-INF/classes。

    //获取定义在src/main/resources文件夹中的配置文件
    ClassPathResource resource = new ClassPathResource("generator.properties");
    Properties properties = new Properties();
    properties.load(resource.getStream());
    LOGGER.info("/classPath:{}", properties);

    4.5 NumberUtil :数字处理工具类

      可用于各种类型数字的加减乘除操作及判断类型。

    double n1 = 1.234;
    double n2 = 1.234;
    double result;
    //对float、double、BigDecimal做加减乘除操作
    result = NumberUtil.add(n1, n2);
    result = NumberUtil.sub(n1, n2);
    result = NumberUtil.mul(n1, n2);
    result = NumberUtil.div(n1, n2);
    //保留两位小数
    BigDecimal roundNum = NumberUtil.round(n1, 2);
    String n3 = "1.234";
    //判断是否为数字、整数、浮点数
    NumberUtil.isNumber(n3);
    NumberUtil.isInteger(n3);
    NumberUtil.isDouble(n3);

    4.6 BeanUtil:JavaBean的工具类

      可用于Map与JavaBean对象的互相转换以及对象属性的拷贝。

    PmsBrand brand = new PmsBrand();
    brand.setId(1L);
    brand.setName("华为");
    brand.setShowStatus(0);
    //Bean转Map
    Map<String, Object> map = BeanUtil.beanToMap(brand);
    LOGGER.info("beanUtil bean to map:{}", map);
    //Map转Bean
    PmsBrand mapBrand = BeanUtil.mapToBean(map, PmsBrand.class, false);
    LOGGER.info("beanUtil map to bean:{}", mapBrand);
    //Bean属性拷贝
    PmsBrand copyBrand = new PmsBrand();
    BeanUtil.copyProperties(brand, copyBrand);
    LOGGER.info("beanUtil copy properties:{}", copyBrand);

    4.7 CollUtil:集合操作的工具类

    //数组转换为列表
    String[] array = new String[]{"a", "b", "c", "d", "e"};
    List<String> list = CollUtil.newArrayList(array);
    //join:数组转字符串时添加连接符号
    String joinStr = CollUtil.join(list, ",");
    LOGGER.info("collUtil join:{}", joinStr);
    //将以连接符号分隔的字符串再转换为列表
    List<String> splitList = StrUtil.split(joinStr, ',');
    LOGGER.info("collUtil split:{}", splitList);
    //创建新的Map、Set、List
    HashMap<Object, Object> newMap = CollUtil.newHashMap();
    HashSet<Object> newHashSet = CollUtil.newHashSet();
    ArrayList<Object> newList = CollUtil.newArrayList();
    //判断列表是否为空
    CollUtil.isEmpty(list);

    4.8 MapUtil:Map操作工具类

      可用于创建Map对象及判断Map是否为空。

    //将多个键值对加入到Map中
    Map<Object, Object> map = MapUtil.of(new String[][]{
        {"key1", "value1"},
        {"key2", "value2"},
        {"key3", "value3"}
    });
    //判断Map是否为空
    MapUtil.isEmpty(map);
    MapUtil.isNotEmpty(map);

    4.9 AnnotationUtil:注解工具类

      可用于获取注解与注解中指定的值。

    //获取指定类、方法、字段、构造器上的注解列表
    Annotation[] annotationList = AnnotationUtil.getAnnotations(HutoolController.class, false);
    LOGGER.info("annotationUtil annotations:{}", annotationList);
    //获取指定类型注解
    Api api = AnnotationUtil.getAnnotation(HutoolController.class, Api.class);
    LOGGER.info("annotationUtil api value:{}", api.description());
    //获取指定类型注解的值
    Object annotationValue = AnnotationUtil.getAnnotationValue(HutoolController.class, RequestMapping.class);

    4.10 SecureUtil:加密解密工具类,可用于MD5加密。

    //MD5加密
    String str = "123456";
    String md5Str = SecureUtil.md5(str);
    LOGGER.info("secureUtil md5:{}", md5Str);

    4.11 CaptchaUtil:验证码工具类,可用于生成图形验证码。

    //生成验证码图片
    LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
    try {
        request.getSession().setAttribute("CAPTCHA_KEY", lineCaptcha.getCode());
        response.setContentType("image/png");//告诉浏览器输出内容为图片
        response.setHeader("Pragma", "No-cache");//禁止浏览器缓存
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        lineCaptcha.write(response.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }

    4.12  其他

      Hutool中的工具类很多,可以参考:https://www.hutool.cn/

  • 相关阅读:
    Commonjs,AMD,CMD和UMD的差异
    ajax中datatype的json和jsonp
    bufferd对象详解
    NodeJS中Buffer模块详解
    Vue 定义组件模板的七种方式(一般用单文件组件更好)
    vuejs 单文件组件.vue 文件
    git clone 带用户名密码
    去掉一组整型数组重复的值
    Vue中在组件销毁时清除定时器(setInterval)
    使用Nginx实现反向代理
  • 原文地址:https://www.cnblogs.com/huanshilang/p/14957395.html
Copyright © 2011-2022 走看看