Just into lines of Java development programmers may in many cases for the realization of some code are manually to achieve, not to say that this is not good, to a certain extent, it is a waste of time, and probably some mistakes, but this is normal, I ve just done when writing the code also is such, but learn to use off-the-shelf tools after class, It might save you a lot of time.

Here I would like to share a few of these tool classes:

String correlation

The String class is probably the one we use most in normal Java development. We often need to do some things around String. The JDK also provides a lot of String apis, but the functionality is quite basic. It is often necessary to combine multiple String methods to accomplish a business function.

The first is the StringUtils utility class provided by Apache

Pom dependencies to introduce:

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

Note: Commons-lang3 is a new version that has been maintained. It is recommended to use this instead of Commons-lang

1. Check whether the string is empty

String str = "hello world";
if (null == str || str.isEmpty()) {
  //do something
}
Copy the code

The above writing must have written, although this code is simple, but it is easy to cause a null pointer exception

StringUtils is written as follows:

if(StringUtils.isEmpty(str)){
//do something
}
Copy the code

Is it easier for the above code to determine if the string is empty, but be aware of the following case

public class UtilsTest {
    public static void main(String[] args) {
        String str1 = "";
        String str2 = "";
        System.out.println(StringUtils.isEmpty(str1));// false
        System.out.println(StringUtils.isEmpty(str2));// true}}Copy the code

2. The string has a fixed length

String result = StringUtils.leftPad("test".8."0");// 0000test
Copy the code

The leftPad method above returns a string of a fixed length of 8, with a zero added to the left if it is insufficient

3. Keyword replacement

// Replace all keywords
StringUtils.replace("abc"."a"."A"); //Abc
// Replace the keyword only once
StringUtils.replaceOnce("aba"."a"."A"); //Aba
// Use regular expression substitution
StringUtils.replacePattern("ABCabc123"."[^A-Z0-9]+".""); //ABC123
Copy the code

4. String concatenation

String[] array = new String[]{"abc"."123"."456"};
StringBuilder stringBuilder = new StringBuilder();
for(String s:array){
stringBuilder.append(s).append(";");
} 
System.out.println(stringBuilder.toString()); //abc; 123; 456
Copy the code

StringUtils class USES

String[] array = new String[]{"abc"."123"."456"};
StringUtils.join(array,";") //abc; 123; 456
Copy the code

5. String splitting

StringUtils.split("a.b.c".".") //["a","b","c"]
Copy the code

Two, date related

DateUtils and DateFormatUtils

Before JDK8, Java provided only one Date class. When we need to convert Date to a string in a certain format, we need to use the SimpleDateFormat class.

1. The date is converted to a string of the specified format

public class UtilsTest {
    public static void main(String[] args) {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // Convert the Date type to the specified string formatString dateString=simpleDateFormat.format(date); System.out.println(dateString); }}Copy the code

Look like is also very simple, but it used SimpleDateFormat isn’t thread-safe, this leads to thread safe problem may come up in a multithreaded environment, therefore, we can use the time under the common – lang3 tools DataUtils/DateFormateUtils, Thus solve the conversion problem between Date and string.

The method is very simple, the above code conversion is equivalent to the following code:

String dateString = DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss");
System.out.println(dateString);
Copy the code

2. String to date

Date date = DateUtils.parseDate("The 2020-10-15 22:00:00"."yyyy-MM-dd HH:mm:ss");
System.out.println(date);
Copy the code

Output result:

Thu Oct 15 22:00:00 CST 2020
Copy the code

3. Calculation of DateUtils time

In addition to the date conversion above, DateUtils also provides a very convenient time calculation function

Post code directly:

Output result:

Third, set array correlation

1. Determine whether it is empty

I used to judge

List<String> list = new ArrayList<String>();
if(null==list||list.isEmpty()){
//do something
}
Copy the code

This is not too hard to write, but it is also easier to throw a null pointer exception. Now we can use the Commons-Collections class to help us determine whether it is null

Pom depends on:

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

Using CollectionUtils/MapUtils/ArrayUtils sentenced to empty

List<String> list = new ArrayList<String>();
Map map = new HashMap();
String[] strings = new String[];
map.put("name"."zxb");

// Check that the list set is empty
if (CollectionUtils.isEmpty(list)) {
  // do something
}
// Determine that map is empty
if (MapUtils.isEmpty(map)){
  //do something
}

// Check that the array is empty
if(ArrayUtils.isEmpty(strings)){
  //do someting 
}

Copy the code

One thing to note is that ArrayUtils is under the Commons-Lang3 package

Add the array to the list quickly

Directly on the code:

Output:

Other methods here do not do too much supplement, you can use IDEA to play with other methods, in fact, Google Guava tool class also has a lot of operations for collection enhancement classes, you can go to search the relevant information

Four, timing related

Previous timing:

long start = System.currentTimeMillis();
long end = System.currentTimeMillis();
System.out.println("Running time:"+(end-start)+"ms");
Copy the code

It’s pretty simple, but it’s pretty inflexible. By default, we can only measure it in ms. What if it takes minutes? That requires additional calculation to convert, I here introduce you to Guava StopWatch timing tool class to count the program execution time

Pom depends on:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>19.0</version>
</dependency>
Copy the code

Use the Stopwatch utility class to count the program execution time:

Output result: