preface

Do you have a leader who likes to see the code? My leader likes to see the code I write. He likes to discuss with me how to write the best. Very good.

Today let’s take a look at third-party open source libraries that can save up to 90% of 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 that operate on strings, dates, arrays, and so on.

Lang3

Lang3 is a package that handles basic objects in Java, such as StringUtils to manipulate strings, ArrayUtils to manipulate arrays, DateUtils to manipulate dates, MutablePair to return 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>Copy the code

String operation

Quick operation on strings, short write null condition on if else.

public static void main(String[] args) { boolean blank = StringUtils.isBlank(" "); System.out.println(blank); boolean empty = StringUtils.isEmpty(" "); // Notice that this is 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"); // Remove the string system.out.println (remove); }Copy the code

Output results:

true
false
true
true
bcdefgh

Process finished with exit code 0

Copy the code

Date of operation

Instead of using SimpleDateFormat to format dates, the 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); Println (date1); // Add a day system.out.println (date1); boolean sameDay = DateUtils.isSameDay(date, new Date()); / / System. Quite out. Println (sameDay); RANGE_WEEK_MONDAY Gets the days of the week from Monday. RANGE_WEEK_RELATIVE gets the days of the week from the current time RANGE_WEEK_CENTER Gets a week's date with the current date as the center RANGE_MONTH_SUNDAY Gets a month's date starting from Sunday RANGE_MONTH_MONDAY Gets a month's date starting from 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")); }}Copy the code

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

Copy the code

Return multiple fields

Sometimes when you need to return more than one value in a method, you often use a HashMap return or a JSON return. Lang3 already provides such a utility class for us, so we don’t need to write any 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, "there are three values ", new Date()); System.out.println(mutableTriple.getLeft() + " " + mutableTriple.getMiddle() + " " + mutableTriple.getRight()); }Copy the code

Output results:

2 These are two values. 2 These are three values Fri Jul 16 15:24:40 CST 2021 Process Finished with exit code 0Copy the code

ArrayUtils Array operation

ArrayUtils is a class that specializes in handling arrays, making it easy to work with arrays rather than 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)); String[] 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 invert: "+ arrayUtils.toString (array4)); <String, String> arrayMap = (HashMap) arrayutils.tomap (new String[][]{{"key1", "value1"}, {"key2", "value2"} }); for (String s : arrayMap.keySet()) { System.out.println(arrayMap.get(s)); }}Copy the code

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 0Copy the code

EnumUtils Enumeration operation

  • GetEnum (Class enumClass, String enumName) returns an enumeration by Class, possibly null;
  • GetEnumList (Class enumClass) returns a collection of enumerations by Class;
  • GetEnumMap (Class enumClass) returns an enumeration map by Class;
  • IsValidEnum (Class enumClass, String enumName) Verifies that enumName is in the enumeration, returning true or False.
public enum ImagesTypeEnum {
    JPG,JPEG,PNG,GIF;
}

Copy the code
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); }Copy the code

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 0Copy the code

Collections4 Collection operation

Commons – CollectionS4 enhances the Java collections framework by providing a set of simple apis for manipulating collections.

Maven rely on

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

CollectionUtils tools

This is a utility class that can check that null elements are not added to a set, merge lists, filter lists, union of two lists, difference sets, and collection. Some of these features can be replaced by the Stream API in Java 8.

Public static void main(String[] args) {// Null elements cannot be added to 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); / / intersection Collection < String > strings. = CollectionUtils retainAll (arrayList4 arrayList3); System.out.println(" intersection of arrayList3 and arrayList4: "+ strings); Union = CollectionUtils. Union (arrayList4, arrayList3); System.out.println(" union of arrayList3 and arrayList4: "+ union); Subtract = CollectionUtils. Subtract (arrayList4, arrayList3); Println (" difference set of arrayList3 and arrayList4: "+ subtract); B CollectionUtils. Filter (arrayList4, s -> s.equals("b")); System.out.println(arrayList4); }Copy the code

Output results:

1 arrayList3 :[C, D] arrayList4:[a, B, C, D] intersection of arrayList3 and arrayList4:[c, D] union of arrayList3 and arrayList4: [a, B, C, D] [a, b] [b] Process finished with exit code 0Copy the code

Bag count

The number of times a statistic appears in a 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"));
}

Copy the code

Output results:

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

Process finished with exit code 0

Copy the code

Beanutils Bean operation

Beanutils operates on Javabeans through a reflection mechanism. For example, copy beans, map to object, object to map.

Maven rely on

< the dependency > < groupId > Commons beanutils - < / groupId > < artifactId > Commons beanutils - < / artifactId > < version > 1.9.4 < / version > </dependency>Copy the code
public class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; }}Copy the code
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()); //User translate map map <String, String> describe = BeanUtils. Describe (user1); System.out.println(describe); User Map<String, String> beanMap = new HashMap(); Beanmap. put("name", "zhang SAN "); User user3 = new User(); BeanUtils.populate(user3, beanMap); System.out.println(user3.getName()); }Copy the code

Output results:

Name = name} Process finished with exit code 0Copy the code

Guava

A Google open source Java-based extension project that includes basic tools, collection extensions, caching, concurrency toolkits, string processing, and more.

Maven rely on

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

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 more complicated.

Public static void main(String[] args) {// Previous Map<String, List<String>> 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 ", "lisi "); System. The out. Println (multimap. Get (" name ")); }Copy the code

Output results:

[Zhang SAN, Li Si] Process finished with exit code 0Copy the code

Value Indicates the Map that cannot be duplicated

While the values of values in a Map can be repeated, Guava can create a Map where the values are not repeated, and Map and value can be interchanged.

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")); }Copy the code

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

Copy the code
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")); BiMap = bimap.inverse (); System.out.println(biMap.get("value1")); }Copy the code

Output results:

value1
key1

Process finished with exit code 0

Copy the code

Guava cache

If you don’t want to use a third-party cache and Map is not powerful enough, you can use Guava’s cache.

Concurrency level of the cache

Guava provides apis for setting concurrency levels so that the cache supports concurrent writes and reads. Similar to ConcurrentHashMap, Guava Cache concurrency is also achieved through separate locks. In general, it is recommended to set the concurrency level to the number of server CPU cores.

Cachebuild.newbuilder () // set the concurrencyLevel to the number of CPU cores. The default is 4.concurrencylevel (runtime.getruntime ().availableprocessors ()).build();Copy the code

The initial capacity setting of the cache

When we build the cache, we can set a reasonable initial capacity for the cache, which is very expensive to expand because Guava’s cache uses a separate lock mechanism. Therefore, a reasonable initial capacity can reduce the number of times the cache container can be expanded.

Cachebuilder.newbuilder () // set the initialCapacity to 100. initialCapacity(100).build();Copy the code

Setting maximum Storage

Guava Cache can specify the maximum number of records that the Cache can store when building the Cache object. When the number of records in the Cache reaches the maximum and an object is added to the Cache by calling the put method, Guava will delete one of the current cached object records to make room for new objects 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
}

Copy the code

Output results:

null

Process finished with exit code 0

Copy the code

Expiration time

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

Public static void main(String[] args) throws InterruptedException {// Set the expiration time to 2 seconds 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")); }Copy the code

Output results:

value1
null

Process finished with exit code 0

Copy the code

LoadingCache

Use a custom ClassLoader to load the data and place it in memory. When data is obtained from LoadingCache, it is returned directly if the data exists. If the data does not exist, the ClassLoader loads the data into memory using the Load method of the ClassLoader 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; }}); }Copy the code

Output results:

no cache
5
5
6

Process finished with exit code 0

Copy the code

conclusion

With Two third-party open source tool libraries, Apache Commons and Guava, you can reduce the code of loops and ifelse. The code is more robust and can be used in front of new people. Apache Commons and Guava have many, many utility classes, but only a few are listed here, and you can see the various uses in the examples on the website.