preface

Do you have a leader who likes to see the code? My leader likes to see the code I write, and he likes to discuss with me about how to write the best, hahaha… Very good.

Today we’re going to take a look at some of the third party open source libraries that can save up to 90% of your overtime. The first one 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 libraries, including operations on strings, dates, arrays, and so on.

Lang3

Lang3 is a package that works with basic objects in Java, such as StringUtils that works with strings, ArrayUtils that works with arrays, DateUtils that works with dates, MutablePair that returns multiple fields, and so on.

Package structure:

Maven rely on

Mons < dependency > < groupId > org.apache.com < / groupId > < artifactId > Commons - lang3 < / artifactId > < version > 3.11 < / version > </dependency>

String manipulation

Faster manipulation of strings, with fewer null conditions written in if else.

public static void main(String[] args) { boolean blank = StringUtils.isBlank(" "); System.out.println(blank); // This is not the same as isEmpty. boolean empty = StringUtils.isEmpty(" "); // Note false system.out.println (empty); boolean anyBlank = StringUtils.isAnyBlank("a", " ", "c"); // One of them is not an empty string System.out.println(anyBlank); boolean numeric = StringUtils.isNumeric("1"); System.out.println(numeric); System.out.println(numeric); System.out.println(numeric); String remove = StringUtils.remove("abcdefgh", "a"); // remove the string System.out.println(remove); }

Output results:

true
false
true
true
bcdefgh

Process finished with exit code 0

Date of operation

Finally, instead of formatting dates in SimpleDateFormat, dateUtils.Iterator can retrieve 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); // add a day to System.out.println(date1); boolean sameDay = DateUtils.isSameDay(date, new Date()); / / System. Quite out. Println (sameDay); /* Gets date of the week from Sunday, range_week_Sunday gets date of the week from Monday, RANGE_WEEK_RELATIVE gets date of the week from the current time RANGE_WEEK_CENTER gets a one-week date based on the current date, range_month_Sunday gets a one-month date starting on Sunday, range_month_Monday gets a one-month date starting on 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 results:

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 from a method, it is common to use HashMap or JSON to return them. Lang3 already provides such utility classes, so we don’t need to write more HashMap and JSON.

Public static void main(String[] args) {mutablePair <Integer, String> mutablePair = mutablePair. Of (2, "These are two values "); System.out.println(mutablePair.getLeft() + " " + mutablePair.getRight()); MutableTriple<Integer, String, Date> mutableTriple = mutableTriple. Of (2, "it's three values ", new Date()); System.out.println(mutableTriple.getLeft() + " " + mutableTriple.getMiddle() + " " + mutableTriple.getRight()); }

Output results:

Fri Jul 16 15:24:40 CST 2021 Process finished with exit code 0

ArrayUtils array operation

ArrayUtils is a class that specializes in working with arrays, making it easier to work with arrays rather than having to loop through them.

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 (array4 = arrayUtils. clone(array3); System.out.println("array4:"+ArrayUtils.toString(array4)); / / array are the same Boolean b = EqualsBuilder. ReflectionEquals (array3, array4); System.out.println(b); // Reverse the array arrayUtils.reverse (array4); System.out.println("array4: "+ arrayUtils.toString (array4)); // ArrayMap <String, String bb0 arrayMap = (HashMap) arrayUtils.tomap (new String[][]{{"key1", "value1"}, {"key2", "value2"} }); for (String s : arrayMap.keySet()) { System.out.println(arrayMap.get(s)); }}

Output results:

Array3: {value1, value2, value3, value4} array4: {value1, value2, value3, value4} true array4 after the reverse: {value4,value3,value2,value1} value1 value2 Process finished with exit code 0

The EnumUtils enumeration operation

  • GetEnum (Class EnumClass, String EnumName) returns an enumeration by Class, possibly null;
  • GetEnumList (Class EnumClass) returns an enumeration collection by Class;
  • GetEnumMap (Class EnumClass) returns an enumeration Map by Class;
  • String EnumName = String EnumName = String EnumName = String EnumName = String EnumName = String EnumName = String EnumName
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. The println (" key: "", the value:" + v +, k +)); 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 results:

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 operation

Commons-Collections4 enhances the Java Collections framework by providing a series of simple APIs to make it easy to manipulate collections.

Maven rely on

Mons < dependency > < groupId > org.apache.com < / groupId > < artifactId > Commons - collections4 < / artifactId > < version > 4.4 < / version > </dependency>

CollectionUtils tools

User-class to check that null elements are not added to sets, to merge lists, to filter lists, and to union, difference, and assembly of two lists. Some of these features can be replaced with the Stream API in Java 8.

Public static void main(String[] args) {List<String arrayList1 = new arrayList <>(); arrayList1.add("a"); CollectionUtils.addIgnoreNull(arrayList1, null); System.out.println(arrayList1.size()); List<String bb0 arrayList2 = new arrayList <>(); arrayList2.add("a"); arrayList2.add("b"); List<String> arrayList3 = new ArrayList<>(); arrayList3.add("c"); arrayList3.add("d"); Println ("arrayList3: "+ arrayList3); println("arrayList3:" + arrayList3); List<String> arrayList4 = CollectionUtils.collate(arrayList2, arrayList3); System.out.println("arrayList4:" + arrayList4); / / intersection Collection < String > strings. = CollectionUtils retainAll (arrayList4 arrayList3); System.out.println(" intersection of arrayList3 and arrayList4: "+ strings); // Unite Collection<String bb0 union = CollectionUtils.union(arrayList4, arrayList3); System.out.println(" union of arrayList3 and arrayList4: "+ union); Subtract <String> subtract = collectionUtis. subtract(arrayList4, arrayList3); System.out.println("arrayList3 and arrayList4: "+ subtract); Filter (arrayList4, s-> s.quals ("b")); // Filter (arrayList4, s-> s.quals ("b")); System.out.println(arrayList4); }

Output results:

1 arrayList3: [c, d] arrayList4: [a, b, c, d] arrayList3 and arrayList4 intersection: [c, d] arrayList3 and arrayList4 and set: [a, b, c, d] arrayList3 and arrayList4: [a, b] [b

Number of Statistics of BAG

Used to count the number of times a value appears in the collection.

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 results:

[2:a,1:b,3:c]
3

Process finished with exit code 0

Beanutils Bean operation

BeanUtils operates on JavaBeans through reflection. For example, copy beans, map to object, and object to map.

Maven rely on

< the 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. Elegantly-named setName (" li si "); User user2 = (User) BeanUtils.cloneBean(user1); System.out.println(user2.getName()); Map map <String, String> describe = beanUtils.describe (user1); System.out.println(describe); //Map to User Map<String, String> beanMap = new HashMap(); BeanMap. put("name", "zhang three "); User user3 = new User(); BeanUtils.populate(user3, beanMap); System.out.println(user3.getName()); }

Output results:

Process finished with exit code 0 {name= exit code 0

Guava

Google is an open source Java-based extension project that includes some basic tools, collection extensions, caching, concurrency toolkits, string handling, and more.

Maven rely on

< the dependency > < groupId > com. Google. Guava < / groupId > < artifactId > guava < / artifactId > < version > 30.1.1 - jre < / version > </dependency>

Map < String, List > type

It is common in Java code to write local variables to Map<String, List> Map. Sometimes the business is a little bit more complicated.

Public static void main(String[] args) {String <String, List<String bb0 > Map = new HashMap<>(); List<String> list = new ArrayList<>(); List. The add (" zhang "); List. The add (" li si "); Map. put(" name ", list); System. The out. Println (map. Get (" name ")); // Now Multimap<String, String> Multimap = arrayListmultimap.create (); Multimap. put(" name ", "three "); Multimap. put(" name ", "Li Si "); System. The out. Println (multimap. Get (" name ")); }

Output results:

[Zhang San, Li Si] Process finished with exit code 0

Value is not duplicated Map

In a Map, the value of the value can be repeated. Guava can create a Map with non-repeatable value, and the Map and value can be exchanged.

Public static void main(String[] args) {String Bimap <String,String BB0 Bimap = hashBimap.create (); biMap.put("key1", "value"); biMap.put("key2", "value"); System.out.println(biMap.get("key1")); }

Output results:

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 inverse Bimap = Bimap. Inverse (); System.out.println(biMap.get("value1")); }

Output results:

value1
key1

Process finished with exit code 0

Guava cache

When writing business, you will definitely use the cache, but when you don’t want to use a third party as the cache, and Map is not powerful enough, you can use Guava’s cache.

The level of concurrency in the cache

Guava provides an API to set the level of concurrency so that the cache supports concurrent writes and reads. Similar to ConcurrentHashMap, concurrency in Guava Cache is achieved by separating locks. In general, it is recommended to set the concurrency level to the number of server CPU cores.

CacheBuilder.newBuilder() // Set the concurrencyLevel to the number of CPU cores. Default is 4.ConcurrencyLevel (Runtime.getRuntime().availableProcessors()).build();

Set the initial capacity of the cache

We can build the cache with a reasonable initial size for the cache, but since Guava’s cache uses a decouple lock mechanism, scaling is very expensive. So reasonable initial capacity can reduce the number of cache container expansion.

CacheBuilder. NewBuilder () // Set the initialCapacity to 100. InitialCapacity (100).build();

Set maximum storage

Guava Cache can specify the maximum number of records that the Cache can hold when building a Cache object. When the number of records in the Cache reaches its maximum value, the put method is called to add an object to the Cache. Guava will delete one of the object records from the Cache to make room for the new object.

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 results:

null

Process finished with exit code 0

Expiration time

ExpireAfterAccess () can set the expiration time of the cache.

Throws InterruptedException {public static void main(String[] args) throws InterruptedException { 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 results:

value1
null

Process finished with exit code 0

LoadingCache

Load the data using a custom ClassLoader and put it in memory. When retrieving data from LoadingCache, if the data exists, it will be returned directly. If the data does not exist, it is loaded into memory according to the load method of the ClassLoader and returned.

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 results:

no cache
5
5
6

Process finished with exit code 0

conclusion

Looping, Ifelse code can be reduced through two third-party open source tool libraries, Apache Commons and Guava. The code is more robust and can be used to impress new people. Apache Commons and Guava have many, many utility classes, but only a few of them are listed here, and you can see the various uses in the examples on the official website.

The last

I am a yard farmer who is still trying to move forward. If this article is helpful to you, remember thumb up, follow yo, thank you!