After many years of work, it turns out that there are many libraries of utility classes that can greatly simplify code and improve development efficiency, but junior developers don’t know about them. These libraries have long been standard in the industry and are used internally by large companies. If only SOMEONE had told me to use these libraries when I started working.

Take a look at some of the toolclass libraries you’ve used.

1. Java has built-in tools

1.1 List collections are concatenated into comma-separated strings

// How to concatenate a list into comma-separated strings A,b,c
List<String> list = Arrays.asList("a"."b"."c");
// The first method can be a stream
String join = list.stream().collect(Collectors.joining(","));
System.out.println(join); / / output a, b, c
// String also has a join method to do this
String join = String.join(",", list);
System.out.println(join); / / output a, b, c
Copy the code

1.2 Comparing two Strings for equality, ignoring case

if (strA.equalsIgnoreCase(strB)) {
  System.out.println("Equal");
}
Copy the code

1.3 Comparing whether two objects are equal

We can use the java.util package to compare Objects’ equality with equals (). We can use the java.util package to compare Objects’ equality with equals ()

Objects.equals(strA, strB);
Copy the code

The source code looks like this

public static boolean equals(Object a, Object b) {
    return(a == b) || (a ! =null && a.equals(b));
}
Copy the code

1.4 Set the intersection of two List sets

List<String> list1 = new ArrayList<>();
list1.add("a");
list1.add("b");
list1.add("c");
List<String> list2 = new ArrayList<>();
list2.add("a");
list2.add("b");
list2.add("d");
list1.retainAll(list2);
System.out.println(list1); // output [a, b]
Copy the code

2. Apache Commons utility class library

Apache Commons is the most powerful and widely used utility class library. There are many sublibraries in apache Commons. Here are some of the most common ones

2.1 Commons-lang, an enhanced version of java.lang

Commons-lang 3 is recommended, some APIS have been optimized, and the original Commons-lang has stopped updating

Maven dependencies are:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>
Copy the code

2.1.1 Nulling the string

CharSequence is the parent class of String, StringBuilder, and StringBuffer.

public static boolean isEmpty(final CharSequence cs) {
    return cs == null || cs.length() == 0;
}

public static boolean isNotEmpty(final CharSequence cs) {
    return! isEmpty(cs); }// Whitespace is removed from the string, such as Spaces, newlines, and tabs
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); }Copy the code

2.1.2 Uppercase letters

String str = "yideng";
String capitalize = StringUtils.capitalize(str);
System.out.println(capitalize); / / output Yideng
Copy the code

2.1.3 Repeatedly Concatenating Strings

String str = StringUtils.repeat("ab".2);
System.out.println(str); / / output abab
Copy the code

2.1.4 Formatting the Date

No more handwritten SimpleDateFormat formatting

// Change the Date type to String
String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
System.out.println(date); // Output 2021-05-01 01:01:01

// Change the String type to Date type
Date date = DateUtils.parseDate("The 2021-05-01 01:01:01"."yyyy-MM-dd HH:mm:ss");

// Calculate the date one hour later
Date date = DateUtils.addHours(new Date(), 1);
Copy the code

2.1.5 Packing temporary Objects

When a method needs to return two or more fields, we usually wrap it as a temporary object. With Pair and Triple, this is no longer necessary

// Return two fields
ImmutablePair<Integer, String> pair = ImmutablePair.of(1."yideng");
System.out.println(pair.getLeft() + "," + pair.getRight()); / / output 1, yideng
// Return three fields
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
Copy the code

2.2 Commons-Collections Collection utility classes

Maven dependencies are:

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

2.2.1 Set nullification

Encapsulates the set null method, the following is the source code:

public static boolean isEmpty(finalCollection<? > coll) {
    return coll == null || coll.isEmpty();
}

public static boolean isNotEmpty(finalCollection<? > coll) {
    return! isEmpty(coll); }Copy the code
// Set the intersection of two sets
Collection<String> collection = CollectionUtils.retainAll(listA, listB);
// Take the union of two sets
Collection<String> collection = CollectionUtils.union(listA, listB);
// Set the difference between two sets
Collection<String> collection = CollectionUtils.subtract(listA, listB);
Copy the code

2.3 Common-beanutils Operation object

Maven depends on:

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>
Copy the code
public class User {
    private Integer id;
    private String name;
}
Copy the code

Setting Object Properties

User user = new User();
BeanUtils.setProperty(user, "id".1);
BeanUtils.setProperty(user, "name"."yideng");
System.out.println(BeanUtils.getProperty(user, "name")); / / output yideng
System.out.println(user); / / output {" id ": 1," name ":" yideng}"
Copy the code

Object and Map transfer each other

// Object to map
Map<String, String> map = BeanUtils.describe(user);
System.out.println(map); / / o {" id ":" 1 ", "name" : "yideng}"
// map to the object
User newUser = new User();
BeanUtils.populate(newUser, map);
System.out.println(newUser); / / output {" id ": 1," name ":" yideng}"
Copy the code

2.4 Commons-io file stream processing

Maven depends on:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.8.0</version>
</dependency>
Copy the code

File processing

File file = new File("demo1.txt");
// Read the file
List<String> lines = FileUtils.readLines(file, Charset.defaultCharset());
// Write to the file
FileUtils.writeLines(new File("demo2.txt"), lines);
// Copy the file
FileUtils.copyFile(srcFile, destFile);
Copy the code

3. Google Guava Library

Maven depends on:

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

3.1 Creating a Collection

List<String> list = Lists.newArrayList();
List<Integer> list = Lists.newArrayList(1.2.3);
/ / reverse list
List<Integer> reverse = Lists.reverse(list);
System.out.println(reverse); // Output [3, 2, 1]
// The list has so many elements that it can be divided into several sets of 10 elements each
List<List<Integer>> partition = Lists.partition(list, 10);
// Create map and set
Map<String, String> map = Maps.newHashMap();
Set<String> set = Sets.newHashSet();
Copy the code

3.2 Collection of black technology

3.2.1 Multimap A HashMap that maps multiple values to one key

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 ": / / output} [1, 2]
// Also returns the bloated Map you used before
Map<String, Collection<Integer>> collectionMap = map.asMap();
Copy the code

Map<String, List>

3.2.1 BiMap A HashMap whose value cannot be repeated

BiMap<String, String> biMap = HashBiMap.create();
// If value is repeated, the put method throws an exception unless forcePut is used
biMap.put("key"."value");
System.out.println(biMap); / / o {" key ":" value "}
// If the value can't be repeated, why not implement a key/value reversal method
BiMap<String, String> inverse = biMap.inverse();
System.out.println(inverse); / / o {" value ":" the key "}
Copy the code

This is actually bidirectional mapping, which is useful in some scenarios.

3.2.3 Table A HashMap with two keys

// A group of users, grouped by age and gender
Table<Integer, String, String> table = HashBasedTable.create();
table.put(18."Male"."yideng");
table.put(18."Female"."Lily");
System.out.println(table.get(18."Male")); / / output yideng
// This is actually a two-dimensional Map, you can view the row data
Map<String, String> row = table.row(18);
System.out.println(row); // output {" male ":"yideng"," female ":"Lily"}
// View column data
Map<Integer, String> column = table.column("Male");
System.out.println(column); / / o {18: "yideng}"
Copy the code

3.2.4 Multiset A Set used for counting

Multiset<String> multiset = HashMultiset.create();
multiset.add("apple");
multiset.add("apple");
multiset.add("orange");
System.out.println(multiset.count("apple")); 2 / / output
// View the de-weighted elements
Set<String> set = multiset.elementSet();
System.out.println(set); / / output/" orange ", "apple"
// You can also view unweighted elements
Iterator<String> iterator = multiset.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}
// You can manually set the number of occurrences of an element
multiset.setCount("apple".5);
Copy the code

What other common tool methods or libraries do you know of?