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
字符串的处理类(StringUtils)
public class DemoArray {
public static void main(String[] args) {
//缩短到某长度,用...结尾.其实就是(substring(str, 0, max-3) + "...")
//public static String abbreviate(String str,int maxWidth)
StringUtils.abbreviate("abcdefg", 6);// ---"abc..."
//字符串结尾的后缀是否与你要结尾的后缀匹配,若不匹配则添加后缀
StringUtils.appendIfMissing("abc","xyz");//---"abcxyz"
StringUtils.appendIfMissingIgnoreCase("abcXYZ","xyz");//---"abcXYZ"
//首字母大小写转换
StringUtils.capitalize("cat");//---"Cat"
StringUtils.uncapitalize("Cat");//---"cat"
//字符串扩充至指定大小且居中(若扩充大小少于原字符大小则返回原字符,若扩充大小为 负数则为0计算 )
StringUtils.center("abcd", 2);//--- "abcd"
StringUtils.center("ab", -1);//--- "ab"
StringUtils.center("ab", 4);//---" ab "
StringUtils.center("a", 4, "yz");//---"yayz"
StringUtils.center("abc", 7, "");//---" abc "
//去除字符串中的"\n", "\r", or "\r\n"
StringUtils.chomp("abc\r\n");//---"abc"
//判断一字符串是否包含另一字符串
StringUtils.contains("abc", "z");//---false
StringUtils.containsIgnoreCase("abc", "A");//---true
//统计一字符串在另一字符串中出现次数
StringUtils.countMatches("abba", "a");//---2
//删除字符串中的梭有空格
StringUtils.deleteWhitespace(" ab c ");//---"abc"
//比较两字符串,返回不同之处。确切的说是返回第二个参数中与第一个参数所不同的字符串
StringUtils.difference("abcde", "abxyz");//---"xyz"
//检查字符串结尾后缀是否匹配
StringUtils.endsWith("abcdef", "def");//---true
StringUtils.endsWithIgnoreCase("ABCDEF", "def");//---true
StringUtils.endsWithAny("abcxyz", new String[] {null, "xyz", "abc"});//---true
//检查起始字符串是否匹配
StringUtils.startsWith("abcdef", "abc");//---true
StringUtils.startsWithIgnoreCase("ABCDEF", "abc");//---true
StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"});//---true
//判断两字符串是否相同
StringUtils.equals("abc", "abc");//---true
StringUtils.equalsIgnoreCase("abc", "ABC");//---true
//比较字符串数组内的所有元素的字符序列,起始一致则返回一致的字符串,若无则返回""
StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"});//---"ab"
//正向查找字符在字符串中第一次出现的位置
StringUtils.indexOf("aabaabaa", "b");//---2
StringUtils.indexOf("aabaabaa", "b", 3);//---5(从角标3后查找)
StringUtils.ordinalIndexOf("aabaabaa", "a", 3);//---1(查找第n次出现的位置)
//反向查找字符串第一次出现的位置
StringUtils.lastIndexOf("aabaabaa", ‘b‘);//---5
StringUtils.lastIndexOf("aabaabaa", ‘b‘, 4);//---2
StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2);//---1
//判断字符串大写、小写
StringUtils.isAllUpperCase("ABC");//---true
StringUtils.isAllLowerCase("abC");//---false
//判断是否为空(注:isBlank与isEmpty 区别)
StringUtils.isBlank(null);StringUtils.isBlank("");StringUtils.isBlank(" ");//---true
StringUtils.isNoneBlank(" ", "bar");//---false
StringUtils.isEmpty(null);StringUtils.isEmpty("");//---true
StringUtils.isEmpty(" ");//---false
StringUtils.isNoneEmpty(" ", "bar");//---true
//判断字符串数字
StringUtils.isNumeric("123");//---true
StringUtils.isNumeric("12 3");//---false (不识别运算符号、小数点、空格……)
StringUtils.isNumericSpace("12 3");//---true
//数组中加入分隔符号
//StringUtils.join([1, 2, 3], ‘;‘);//---"1;2;3"
//大小写转换
StringUtils.upperCase("aBc");//---"ABC"
StringUtils.lowerCase("aBc");//---"abc"
StringUtils.swapCase("The dog has a BONE");//---"tHE DOG HAS A bone"
//替换字符串内容……(replacePattern、replceOnce)
StringUtils.replace("aba", "a", "z");//---"zbz"
StringUtils.overlay("abcdef", "zz", 2, 4);//---"abzzef"(指定区域)
StringUtils.replaceEach("abcde", new String[]{"ab", "d"},
new String[]{"w", "t"});//---"wcte"(多组指定替换ab->w,d->t)
//重复字符
StringUtils.repeat(‘e‘, 3);//---"eee"
//反转字符串
StringUtils.reverse("bat");//---"tab"
//删除某字符
StringUtils.remove("queued", ‘u‘);//---"qeed"
//分割字符串
StringUtils.split("a..b.c", ‘.‘);//---["a", "b", "c"]
StringUtils.split("ab:cd:ef", ":", 2);//---["ab", "cd:ef"]
StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 2);//---["ab", "cd-!-ef"]
StringUtils.splitByWholeSeparatorPreserveAllTokens("ab::cd:ef", ":");//-["ab"," ","cd","ef"]
//去除首尾空格,类似trim……(stripStart、stripEnd、stripAll、stripAccents)
StringUtils.strip(" ab c ");//---"ab c"
StringUtils.stripToNull(null);//---null
StringUtils.stripToEmpty(null);//---""
//截取字符串
StringUtils.substring("abcd", 2);//---"cd"
StringUtils.substring("abcdef", 2, 4);//---"cd"
//left、right从左(右)开始截取n位字符
StringUtils.left("abc", 2);//---"ab"
StringUtils.right("abc", 2);//---"bc"
//从第n位开始截取m位字符 n m
StringUtils.mid("abcdefg", 2, 4);//---"cdef"
StringUtils.substringBefore("abcba", "b");//---"a"
StringUtils.substringBeforeLast("abcba", "b");//---"abc"
StringUtils.substringAfter("abcba", "b");//---"cba"
StringUtils.substringAfterLast("abcba", "b");//---"a"
StringUtils.substringBetween("tagabctag", "tag");//---"abc"
StringUtils.substringBetween("yabczyabcz", "y", "z");//---"abc"
}
}
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);
}
// 两个集合取交集
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 操作对象
<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 文件流处理
<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<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();
3.2.2 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);
3.3将集合转换为特定规则的字符串
//use java
List<String> list = new ArrayList<String>();
list.add("aa");
list.add("bb");
list.add("cc");
String str = "";
for(int i=0; i<list.size(); i++){
str = str + "-" +list.get(i);
}
//str 为-aa-bb-cc
//use guava
List<String> list = new ArrayList<String>();
list.add("aa");
list.add("bb");
list.add("cc");
String result = Joiner.on("-").join(list);
//result为 aa-bb-cc
把map集合转换为特定规则的字符串
Map<String, Integer> map = Maps.newHashMap();
map.put("xiaoming", 12);
map.put("xiaohong",13);
String result = Joiner.on(",").withKeyValueSeparator("=").join(map);
// result为 xiaoming=12,xiaohong=13
33.将String转换为特定的集合
//use java
List<String> list = new ArrayList<String>();
String a = "1-2-3-4-5-6";
String[] strs = a.split("-");
for(int i=0; i<strs.length; i++){
list.add(strs[i]);
}
//use guava
String str = "1-2-3-4-5-6";
List<String> list = Splitter.on("-").splitToList(str);
//list为 [1, 2, 3, 4, 5, 6]
如果
如果
str="1-2-3-4- 5- 6 ";
guava还可以使用 omitEmptyStrings().trimResults()
去除空串与空格
String str = "1-2-3-4- 5- 6 ";
List<String> list = Splitter.on("-").omitEmptyStrings().trimResults().splitToList(str);
System.out.println(list);
将String转换为map
String str = "xiaoming=11,xiaohong=23";
Map<String,String> map = Splitter.on(",").withKeyValueSeparator("=").split(str);