Preface
You have some leaders who like to look at the code, and my leaders like to read the code I wrote. If you have anything to do, you like to discuss with me how to write the best, hahaha...it's good.
Today, let’s take a look at a third-party open source library that can save 90% of overtime. The first introduction must be the Commons library under Apache. The second is Google's open source Guava library.
Apache Commons
Apache Commons is a very powerful and frequently used library. It has about 40 class libraries, including operations on strings, dates, arrays, etc.
Lang3
Lang3 is a package that handles basic objects in Java, such as StringUtils to manipulate strings, ArrayUtils to manipulate arrays, DateUtils to process dates, MutablePair to return multiple fields, and so on.
package structure:
maven dependency
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
String manipulation
For quick operation of strings, write less null condition in if else.
public static void main(String[] args) {
boolean blank = StringUtils.isBlank(" ");//注意此处是null哦 这和isEmpty不一样的
System.out.println(blank);
boolean empty = StringUtils.isEmpty(" ");//注意这里是false
System.out.println(empty);
boolean anyBlank = StringUtils.isAnyBlank("a", " ", "c");// 其中一个是不是空字符串
System.out.println(anyBlank);
boolean numeric = StringUtils.isNumeric("1");//字符串是不是全是数字组成,"." 不算数字
System.out.println(numeric);
String remove = StringUtils.remove("abcdefgh", "a");//移除字符串
System.out.println(remove);
}
Output result:
true
false
true
true
bcdefgh
Process finished with exit code 0
Date operation
Finally, you can format the date without SimpleDateFormat, and DateUtils.iterator can get a period of time.
public static void main(String[] args) throws ParseException {
Date date = DateUtils.parseDate("2021-07-15", "yyyy-MM-dd");
Date date1 = DateUtils.addDays(date, 1);//加一天
System.out.println(date1);
boolean sameDay = DateUtils.isSameDay(date, new Date());//比较
System.out.println(sameDay);
/*
获取一段日期
RANGE_WEEK_SUNDAY 从周日开始获取一周日期
RANGE_WEEK_MONDAY 从周一开始获取一周日期
RANGE_WEEK_RELATIVE 从当前时间开始获取一周日期
RANGE_WEEK_CENTER 以当前日期为中心获取一周日期
RANGE_MONTH_SUNDAY 从周日开始获取一个月日期
RANGE_MONTH_MONDAY 从周一开始获取一个月日期
*/
Iterator<Calendar> iterator = DateUtils.iterator(date, DateUtils.RANGE_WEEK_CENTER);
while (iterator.hasNext()) {
Calendar next = iterator.next();
System.out.println(DateFormatUtils.format(next, "yyyy-MM-dd"));
}
}
Output result:
Fri Jul 16 00:00:00 CST 2021
false
2021-07-12
2021-07-13
2021-07-14
2021-07-15
2021-07-16
2021-07-17
2021-07-18
Process finished with exit code 0
Return multiple fields
Sometimes when multiple values need to be returned in a method, HashMap return or JSON return are often used. Lang3 has already provided us with such tools, so there is no need to write more HashMap and JSON.
public static void main(String[] args) {
MutablePair<Integer, String> mutablePair = MutablePair.of(2, "这是两个值");
System.out.println(mutablePair.getLeft() + " " + mutablePair.getRight());
MutableTriple<Integer, String, Date> mutableTriple = MutableTriple.of(2, "这是三个值", new Date());
System.out.println(mutableTriple.getLeft() + " " + mutableTriple.getMiddle() + " " + mutableTriple.getRight());
}
Output result:
2 这是两个值
2 这是三个值 Fri Jul 16 15:24:40 CST 2021
Process finished with exit code 0
ArrayUtils array operations
ArrayUtils is a class that specializes in processing arrays, which allows convenient processing of arrays instead of requiring various loop operations.
public static void main(String[] args) {
//合并数组
String[] array1 = new String[]{"value1", "value2"};
String[] array2 = new String[]{"value3", "value4"};
String[] array3 = ArrayUtils.addAll(array1, array2);
System.out.println("array3:"+ArrayUtils.toString(array3));
//clone 数组
String[] array4 = ArrayUtils.clone(array3);
System.out.println("array4:"+ArrayUtils.toString(array4));
//数组是否相同
boolean b = EqualsBuilder.reflectionEquals(array3, array4);
System.out.println(b);
//反转数组
ArrayUtils.reverse(array4);
System.out.println("array4反转后:"+ArrayUtils.toString(array4));
//二维数组转 map
Map<String, String> arrayMap = (HashMap) ArrayUtils.toMap(new String[][]{
{"key1", "value1"}, {"key2", "value2"}
});
for (String s : arrayMap.keySet()) {
System.out.println(arrayMap.get(s));
}
}
Output result:
array3:{value1,value2,value3,value4}
array4:{value1,value2,value3,value4}
true
array4反转后:{value4,value3,value2,value1}
value1
value2
Process finished with exit code 0
EnumUtils enumeration operation
- getEnum(Class enumClass, String enumName) returns an enumeration through the class, which may return null;
- getEnumList(Class enumClass) returns an enumeration collection by class;
- getEnumMap(Class enumClass) returns an enumeration map by class;
- isValidEnum(Class enumClass, String enumName) Verify whether enumName is in the enumeration and return true or false.
public enum ImagesTypeEnum {
JPG,JPEG,PNG,GIF;
}
public static void main(String[] args) {
ImagesTypeEnum imagesTypeEnum = EnumUtils.getEnum(ImagesTypeEnum.class, "JPG");
System.out.println("imagesTypeEnum = " + imagesTypeEnum);
System.out.println("--------------");
List<ImagesTypeEnum> imagesTypeEnumList = EnumUtils.getEnumList(ImagesTypeEnum.class);
imagesTypeEnumList.stream().forEach(
imagesTypeEnum1 -> System.out.println("imagesTypeEnum1 = " + imagesTypeEnum1)
);
System.out.println("--------------");
Map<String, ImagesTypeEnum> imagesTypeEnumMap = EnumUtils.getEnumMap(ImagesTypeEnum.class);
imagesTypeEnumMap.forEach((k, v) -> System.out.println("key:" + k + ",value:" + v));
System.out.println("-------------");
boolean result = EnumUtils.isValidEnum(ImagesTypeEnum.class, "JPG");
System.out.println("result = " + result);
boolean result1 = EnumUtils.isValidEnum(ImagesTypeEnum.class, null);
System.out.println("result1 = " + result1);
}
Output result:
imagesTypeEnum = JPG
--------------
imagesTypeEnum1 = JPG
imagesTypeEnum1 = JPEG
imagesTypeEnum1 = PNG
imagesTypeEnum1 = GIF
--------------
key:JPG,value:JPG
key:JPEG,value:JPEG
key:PNG,value:PNG
key:GIF,value:GIF
-------------
result = true
result1 = false
Process finished with exit code 0
collections4 collection operations
commons-collections4 enhances the Java collection framework and provides a series of simple APIs to facilitate the manipulation of collections.
maven dependency
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
CollectionUtils tool class
This is a tool class that can check that null elements are not added to the set, merge lists, filter lists, union, difference, and collection of two lists. Some functions can be replaced by Stream API in Java 8.
public static void main(String[] args) {
//null 元素不能加进去
List<String> arrayList1 = new ArrayList<>();
arrayList1.add("a");
CollectionUtils.addIgnoreNull(arrayList1, null);
System.out.println(arrayList1.size());
//排好序的集合,合并后还是排序的
List<String> arrayList2 = new ArrayList<>();
arrayList2.add("a");
arrayList2.add("b");
List<String> arrayList3 = new ArrayList<>();
arrayList3.add("c");
arrayList3.add("d");
System.out.println("arrayList3:" + arrayList3);
List<String> arrayList4 = CollectionUtils.collate(arrayList2, arrayList3);
System.out.println("arrayList4:" + arrayList4);
//交集
Collection<String> strings = CollectionUtils.retainAll(arrayList4, arrayList3);
System.out.println("arrayList3和arrayList4的交集:" + strings);
//并集
Collection<String> union = CollectionUtils.union(arrayList4, arrayList3);
System.out.println("arrayList3和arrayList4的并集:" + union);
//差集
Collection<String> subtract = CollectionUtils.subtract(arrayList4, arrayList3);
System.out.println("arrayList3和arrayList4的差集:" + subtract);
// 过滤,只保留 b
CollectionUtils.filter(arrayList4, s -> s.equals("b"));
System.out.println(arrayList4);
}
Output result:
1
arrayList3:[c, d]
arrayList4:[a, b, c, d]
arrayList3和arrayList4的交集:[c, d]
arrayList3和arrayList4的并集:[a, b, c, d]
arrayList3和arrayList4的差集:[a, b]
[b]
Process finished with exit code 0
Bag statistics
Used to count the number of times the value appears in the set.
public static void main(String[] args) {
Bag bag = new HashBag<String>();
bag.add("a");
bag.add("b");
bag.add("a");
bag.add("c", 3);
System.out.println(bag);
System.out.println(bag.getCount("c"));
}
Output result:
[2:a,1:b,3:c]
3
Process finished with exit code 0
beanutils Bean operations
Beanutils operates JavaBeans through the reflection mechanism. For example, copy Bean, map to object, and object to Map.
maven dependency
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static void main(String[] args) throws Exception {
User user1 = new User();
user1.setName("李四");
User user2 = (User) BeanUtils.cloneBean(user1);
System.out.println(user2.getName());
//User 转 map
Map<String, String> describe = BeanUtils.describe(user1);
System.out.println(describe);
//Map 转 User
Map<String, String> beanMap = new HashMap();
beanMap.put("name", "张三");
User user3 = new User();
BeanUtils.populate(user3, beanMap);
System.out.println(user3.getName());
}
Output result:
李四
{name=李四}
张三
Process finished with exit code 0
Guava
A Java-based extension project open sourced by Google includes some basic tools, collection extensions, caching, concurrency toolkits, string processing, etc.
maven dependency
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.1.1-jre</version>
</dependency>
Map<String, List> type
In java code, we often encounter the need to write local variables of Map<String, List> map. Sometimes the business situation is a little more complicated.
public static void main(String[] args) {
//以前
Map<String, List<String>> map = new HashMap<>();
List<String> list = new ArrayList<>();
list.add("张三");
list.add("李四");
map.put("名称", list);
System.out.println(map.get("名称"));
//现在
Multimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("名称", "张三");
multimap.put("名称", "李四");
System.out.println(multimap.get("名称"));
}
Output result:
[张三, 李四]
[张三, 李四]
Process finished with exit code 0
Map whose value cannot be repeated
The value of the value in the Map can be repeated, Guava can create a non-repeatable Map, and the Map and value can be reversed.
public static void main(String[] args) {
//会报异常
BiMap<String ,String> biMap = HashBiMap.create();
biMap.put("key1", "value");
biMap.put("key2", "value");
System.out.println(biMap.get("key1"));
}
Output result:
Exception in thread "main" java.lang.IllegalArgumentException: value already present: value
at com.google.common.collect.HashBiMap.put(HashBiMap.java:287)
at com.google.common.collect.HashBiMap.put(HashBiMap.java:262)
at org.example.clone.Test.main(Test.java:17)
Process finished with exit code 1
public static void main(String[] args) {
BiMap<String ,String> biMap = HashBiMap.create();
biMap.put("key1", "value1");
biMap.put("key2", "value2");
System.out.println(biMap.get("key1"));
//key-value 对调
biMap = biMap.inverse();
System.out.println(biMap.get("value1"));
}
Output result:
value1
key1
Process finished with exit code 0
Guava cache
When writing business, you will definitely use cache. When you don't want to use a third party as a cache, Map is not powerful enough, you can use Guava's cache.
Concurrency level of the cache
API
to set the concurrency level, so that the cache supports concurrent writing and reading. Similar to ConcurrentHashMap
, the concurrency of Guava cache is also achieved by separating locks. Under normal circumstances, it is recommended to set the concurrency level to the number of server cpu cores.
CacheBuilder.newBuilder()
// 设置并发级别为cpu核心数,默认为4
.concurrencyLevel(Runtime.getRuntime().availableProcessors())
.build();
Initial cache capacity setting
We can set a reasonable initial capacity for the cache when constructing the cache. Since Guava's cache uses a separate lock mechanism, the cost of expansion is very expensive. Therefore, a reasonable initial capacity can reduce the number of expansions of the cache container.
CacheBuilder.newBuilder()
// 设置初始容量为100
.initialCapacity(100)
.build();
Set maximum storage
Guava Cache can specify the maximum number of records that the cache can store when constructing the cache object. When the number of records in the Cache reaches the maximum value and then call the put method to add objects to it, Guava will first select one of the currently cached object records to delete, and make room for the new object to be stored in the Cache.
public static void main(String[] args) {
Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(2).build();
cache.put("key1", "value1");
cache.put("key2", "value2");
cache.put("key3", "value3");
System.out.println(cache.getIfPresent("key1")); //key1 = null
}
Output result:
null
Process finished with exit code 0
expire date
expireAfterAccess() can set the expiration time of the cache.
public static void main(String[] args) throws InterruptedException {
//设置过期时间为2秒
Cache<String, String> cache1 = CacheBuilder.newBuilder().maximumSize(2).expireAfterAccess(2, TimeUnit.SECONDS).build();
cache1.put("key1", "value1");
Thread.sleep(1000);
System.out.println(cache1.getIfPresent("key1"));
Thread.sleep(2000);
System.out.println(cache1.getIfPresent("key1"));
}
Output result:
value1
null
Process finished with exit code 0
LoadingCache
Use custom ClassLoader
load data and put it into memory. From LoadingCache
acquiring the data, if data is present directly returns; If the data does not exist, according to ClassLoader
of load
loading data into memory it, and returns the data.
public class Test {
public static void main(String[] args) throws Exception {
System.out.println(numCache.get(1));
Thread.sleep(1000);
System.out.println(numCache.get(1));
Thread.sleep(1000);
numCache.put(1, 6);
System.out.println(numCache.get(1));
}
private static LoadingCache<Integer, Integer> numCache = CacheBuilder.newBuilder().
expireAfterWrite(5L, TimeUnit.MINUTES).
maximumSize(5000L).
build(new CacheLoader<Integer, Integer>() {
@Override
public Integer load(Integer key) throws Exception {
System.out.println("no cache");
return key * 5;
}
});
}
Output result:
no cache
5
5
6
Process finished with exit code 0
to sum up
Through the two third-party open source tool libraries, Apache Commons and Guava, the loop and ifelse code can be reduced. The code written is more robust and can be installed in front of newcomers. Apache Commons and Guava have many tools. Only a small part is listed here. You can see various usages in the examples on the official website.
At last
I am a code farmer who is being beaten and working hard to advance. If the article is helpful to you, remember to like and follow, thank you!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。