51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

手机号码,快捷登录

查看: 3959|回复: 0
打印 上一主题 下一主题

[转贴] Java必会的工具库,让你的代码量减少90%

[复制链接]
  • TA的每日心情
    擦汗
    昨天 08:46
  • 签到天数: 981 天

    连续签到: 1 天

    [LV.10]测试总司令

    跳转到指定楼层
    1#
    发表于 2021-7-1 09:42:09 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
     工作很多年后,才发现有很多工具类库,可以大大简化代码量,提升开发效率,初级开发者却不知道。而这些类库早就成为了业界标准类库,大公司的内部也都在使用,如果刚工作的时候就有人告诉我使用这些工具类库,该多好!
      一块看一下有哪些工具类库你也用过。
      1. Java自带工具方法
      1.1 List集合拼接成以逗号分隔的字符串
    1. // 如何把list集合拼接成以逗号分隔的字符串 a,b,c   
    2.   List<String> list = Arrays.asList("a", "b", "c");   
    3.   // 第一种方法,可以用stream流   
    4.   String join = list.stream().collect(Collectors.joining(","));   
    5.   System.out.println(join); // 输出 a,b,c   
    6.   // 第二种方法,其实String也有join方法可以实现这个功能   
    7.   String join = String.join(",", list);   
    8.   System.out.println(join); // 输出 a,b,c
    复制代码
    1.2 比较两个字符串是否相等,忽略大小写
    1.  if (strA.equalsIgnoreCase(strB)) {   
    2.     System.out.println("相等");   
    3.   }   
    复制代码
    1.3 比较两个对象是否相等
      当我们用equals比较两个对象是否相等的时候,还需要对左边的对象进行判空,不然可能会报空指针异常,我们可以用java.util包下Objects封装好的比较是否相等的方法。
    1. Objects.equals(strA, strB);   
    复制代码
    源码是这样的:
    1. public static boolean equals(Object a, Object b) {   
    2.       return (a == b) || (a != null && a.equals(b));   
    3.   }  
    复制代码
    1.4 两个List集合取交集
    1. List<String> list1 = new ArrayList<>();   
    2.   list1.add("a");   
    3.   list1.add("b");   
    4.   list1.add("c");   
    5.   List<String> list2 = new ArrayList<>();   
    6.   list2.add("a");   
    7.   list2.add("b");   
    8.   list2.add("d");   
    9.   list1.retainAll(list2);   
    10.   System.out.println(list1); // 输出[a, b]   
    复制代码
    2. apache commons工具类库
      apache commons是最强大的,也是使用最广泛的工具类库,里面的子库非常多,下面介绍几个最常用的。
      2.1 commons-lang,java.lang的增强版
      建议使用commons-lang3,优化了一些api,原来的commons-lang已停止更新。
      Maven依赖是:
    1. <dependency>   
    2.       <groupId>org.apache.commons</groupId>   
    3.       <artifactId>commons-lang3</artifactId>   
    4.       <version>3.12.0</version>   
    5.   </dependency>   
    复制代码
    2.1.1 字符串判空
      传参CharSequence类型是String、StringBuilder、StringBuffer的父类,都可以直接下面方法判空,以下是源码:
    1. public static boolean isEmpty(final CharSequence cs) {   
    2.       return cs == null || cs.length() == 0;   
    3.   }      
    4.   public static boolean isNotEmpty(final CharSequence cs) {   
    5.       return !isEmpty(cs);   
    6.   }      
    7.   // 判空的时候,会去除字符串中的空白字符,比如空格、换行、制表符   
    8.   public static boolean isBlank(final CharSequence cs) {   
    9.       final int strLen = length(cs);   
    10.       if (strLen == 0) {   
    11.           return true;   
    12.       }   
    13.       for (int i = 0; i < strLen; i++) {   
    14.           if (!Character.isWhitespace(cs.charAt(i))) {   
    15.               return false;   
    16.           }   
    17.       }   
    18.       return true;   
    19.   }     
    20.   public static boolean isNotBlank(final CharSequence cs) {   
    21.       return !isBlank(cs);   
    22.   }   
    复制代码
    2.1.2 首字母转成大写
    1. String str = "yideng";   
    2.   String capitalize = StringUtils.capitalize(str);   
    3.   System.out.println(capitalize); // 输出Yideng
    复制代码
     2.1.3 重复拼接字符串
    1. String str = StringUtils.repeat("ab", 2);   
    2.   System.out.println(str); // 输出abab   
    复制代码
     2.1.4 格式化日期
      再也不用手写SimpleDateFormat格式化了
    1.  // Date类型转String类型   
    2.   String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");   
    3.   System.out.println(date); // 输出 2021-05-01 01:01:01      
    4.   // String类型转Date类型   
    5.   Date date = DateUtils.parseDate("2021-05-01 01:01:01", "yyyy-MM-dd HH:mm:ss");   
    6.     // 计算一个小时后的日期   
    7.   Date date = DateUtils.addHours(new Date(), 1);   
    复制代码
    2.1.5 包装临时对象
      当一个方法需要返回两个及以上字段时,我们一般会封装成一个临时对象返回,现在有了Pair和Triple就不需要了。
    1.  // 返回两个字段   
    2.   ImmutablePair<Integer, String> pair = ImmutablePair.of(1, "yideng");   
    3.   System.out.println(pair.getLeft() + "," + pair.getRight()); // 输出 1,yideng   
    4.   // 返回三个字段   
    5.   ImmutableTriple<Integer, String, Date> triple = ImmutableTriple.of(1, "yideng", new Date());   
    6.   System.out.println(triple.getLeft() + "," + triple.getMiddle() + "," + triple.getRight()); // 输出 1,yideng,Wed Apr 07 23:30:00 CST 2021   
    复制代码
    2.2 commons-collections 集合工具类
      Maven依赖是:
    1. <dependency>   
    2.       <groupId>org.apache.commons</groupId>   
    3.       <artifactId>commons-collections4</artifactId>   
    4.       <version>4.4</version>   
    5.   </dependency>   
    复制代码
    2.2.1 集合判空
      封装了集合判空的方法,以下是源码:
    1. public static boolean isEmpty(final Collection<?> coll) {   
    2.       return coll == null || coll.isEmpty();   
    3.   }      
    4.   public static boolean isNotEmpty(final Collection<?> coll) {   
    5.       return !isEmpty(coll);   
    6.   }   
    7.   // 两个集合取交集   
    8.   Collection<String> collection = CollectionUtils.retainAll(listA, listB);   
    9.   // 两个集合取并集   
    10.   Collection<String> collection = CollectionUtils.union(listA, listB);   
    11.   // 两个集合取差集   
    12.   Collection<String> collection = CollectionUtils.subtract(listA, listB);
    复制代码
    2.3 common-beanutils 操作对象
      Maven依赖:
    1. <dependency>   
    2.       <groupId>commons-beanutils</groupId>   
    3.       <artifactId>commons-beanutils</artifactId>   
    4.       <version>1.9.4</version>   
    5.   </dependency>   
    6.   public class User {   
    7.       private Integer id;   
    8.       private String name;   
    9.   }   
    复制代码
    设置对象属性
    1. User user = new User();   
    2.   BeanUtils.setProperty(user, "id", 1);  
    3.   BeanUtils.setProperty(user, "name", "yideng");   
    4.   System.out.println(BeanUtils.getProperty(user, "name")); // 输出 yideng   
    5.   System.out.println(user); // 输出 {"id":1,"name":"yideng"}   
    复制代码
    对象和map互转
    1.  // 对象转map   
    2.   Map<String, String> map = BeanUtils.describe(user);   
    3.   System.out.println(map); // 输出 {"id":"1","name":"yideng"}   
    4.   // map转对象   
    5.   User newnewUser = new User();   
    6.   BeanUtils.populate(newUser, map);   
    7.   System.out.println(newUser); // 输出 {"id":1,"name":"yideng"}   
    复制代码
    2.4 commons-io 文件流处理
      Maven依赖:
    1. <dependency>   
    2.       <groupId>commons-io</groupId>   
    3.       <artifactId>commons-io</artifactId>  
    4.        <version>2.8.0</version>   
    5.   </dependency>   
    复制代码
    文件处理
    1. File file = new File("demo1.txt");  
    2.   // 读取文件   
    3.   List<String> lines = FileUtils.readLines(file, Charset.defaultCharset());   
    4.   // 写入文件   
    5.   FileUtils.writeLines(new File("demo2.txt"), lines);   
    6.   // 复制文件   
    7.   FileUtils.copyFile(srcFile, destFile);   
    复制代码
     3. Google Guava 工具类库
      Maven依赖:
    1. <dependency>   
    2.       <groupId>com.google.guava</groupId>   
    3.       <artifactId>guava</artifactId>   
    4.       <version>30.1.1-jre</version>   
    5.   </dependency>   
    复制代码
    3.1 创建集合
    1.  List<String> list = Lists.newArrayList();   
    2.   List<Integer> list = Lists.newArrayList(1, 2, 3);   
    3.   // 反转list   
    4.   List<Integer> reverse = Lists.reverse(list);   
    5.   System.out.println(reverse); // 输出 [3, 2, 1]   
    6.    // list集合元素太多,可以分成若干个集合,每个集合10个元素   
    7.   List<List<Integer>> partition = Lists.partition(list, 10);   
    8.   Map<String, String> map = Maps.newHashMap();   
    9.   Set<String> set = Sets.newHashSet();   
    复制代码
    3.2 黑科技集合
      3.2.1 Multimap 一个key可以映射多个value的HashMap
    1.  Multimap<String, Integer> map = ArrayListMultimap.create();  
    2.   map.put("key", 1);   
    3.   map.put("key", 2);   
    4.   Collection<Integer> values = map.get("key");   
    5.   System.out.println(map); // 输出 {"key":[1,2]}   
    6.   // 还能返回你以前使用的臃肿的Map   
    7.   Map<String, Collection<Integer>> collectionMap = map.asMap();   
    复制代码
     多省事,多简洁,省得你再创建 Map<String, List>
      3.2.2 BiMap 一种连value也不能重复的HashMap
    1.   BiMap<String, String> biMap = HashBiMap.create();   
    2.   // 如果value重复,put方法会抛异常,除非用forcePut方法   
    3.   biMap.put("key","value");   
    4.   System.out.println(biMap); // 输出 {"key":"value"}   
    5.   // 既然value不能重复,何不实现个翻转key/value的方法,已经有了   
    6.   BiMap<String, String> inverse = biMap.inverse();   
    7.   System.out.println(inverse); // 输出 {"value":"key"}   
    复制代码
    这其实是双向映射,在某些场景还是很实用的。
      3.2.3 Table 一种有两个key的HashMap



    1. // 一批用户,同时按年龄和性别分组   
    2.   Table<Integer, String, String> table = HashBasedTable.create();   
    3.   table.put(18, "男", "yideng");   
    4.   table.put(18, "女", "Lily");   
    5.   System.out.println(table.get(18, "男")); // 输出 yideng  
    6.   // 这其实是一个二维的Map,可以查看行数据   
    7.   Map<String, String> row = table.row(18);   
    8.   System.out.println(row); // 输出 {"男":"yideng","女":"Lily"}   
    9.   // 查看列数据   
    10.   Map<Integer, String> column = table.column("男");   
    11.   System.out.println(column); // 输出 {18:"yideng"}   
    复制代码
    3.2.4 Multiset 一种用来计数的Set
    1. Multiset<String> multiset = HashMultiset.create();   
    2.   multiset.add("apple");   
    3.   multiset.add("apple");   
    4.   multiset.add("orange");   
    5.   System.out.println(multiset.count("apple")); // 输出 2   
    6.   // 查看去重的元素   
    7.   Set<String> set = multiset.elementSet();   
    8.   System.out.println(set); // 输出 ["orange","apple"]  
    9.   // 还能查看没有去重的元素   
    10.   Iterator<String> iterator = multiset.iterator();   
    11.   while (iterator.hasNext()) {   
    12.       System.out.println(iterator.next());   
    13.   }   
    14.   // 还能手动设置某个元素出现的次数   
    15.   multiset.setCount("apple", 5);
    复制代码
     以上为个人经验,希望能给大家一个参考,如有错误或未考虑完全的地方,望不吝赐教。



























    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /2 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-7-9 05:11 , Processed in 0.065105 second(s), 23 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表