In the vast system of the Java language, there are actually many good small tools that can greatly improve our development efficiency. But if you don’t know about them, you are likely to repeatedly write some similar tools. Not only is it a waste of time, but what you write may not be as good as the existing ones.

Today, I have decided to share some small tools that I often use with everyone. I hope they will be helpful to you.

This article will share 9 small tools that we will definitely use in our daily work. The main contents are as follows:

1. Collections

First up is the Collections class under the java.util package. This class is mainly used to operate on collections or return collections. I personally like to use it very much. Here are some commonly used functions:

In work, there is often a need to sort collections. Let’s see how ascending and descending order can be achieved using the Collections tool:

List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
Collections.sort(list); //ASC
System.out.println(list);
Collections.reverse(list); //DESC
System.out.println(list);

Output:

[1, 2, 3]
[3, 2, 1]

Sometimes it is necessary to find the maximum or minimum value in a collection. At this time, you can use the max and min methods of Collections.

For example:

List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
Integer max = Collections.max(list);
Integer min = Collections.min(list);
System.out.println(max);
System.out.println(min);

Output:

3
1

Sometimes, after checking for null, we need to return an empty collection. We can use the emptyList method. For example:

private List<Integer> fun(List<Integer> list) {
if (list == null || list.size() == 0) {
return Collections.emptyList();
}
// ...
return list;
}

To prevent subsequent programs from modifying the result of a certain collection, sometimes we need to define a certain collection as unmodifiable. This can be easily achieved by using the unmodifiablexxx method of Collections:

List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);

List<Integer> integers = Collections.unmodifiableList(list);
integers.add(4);
System.out.println(integers);

Output:

We all know that many collections in Java, such as ArrayList, LinkedList, HashMap, HashSet, etc., are not thread-safe.

In other words, in a multi-threaded environment, adding data to these collections will cause exceptions.

At this time, you can use the synchronizedxxx method of Collections to directly convert these thread-unsafe collections into thread-safe collections. For example:

List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);

List<Integer> integers = Collections.synchronizedList(list); //Converting an ArrayList to a Thread-Safe Collection
System.out.println(integers);

Its underlying implementation will create the SynchronizedRandomAccessList or SynchronizedList class. Many methods of these two classes will be locked with synchronized.

Of course, there are many commonly used methods in the Collections tool class. They will not be introduced one by one here. You need to explore them on your own.

2. CollectionUtils

For collection operations, in addition to the aforementioned Collections tool class, the CollectionUtils tool class is also very commonly used.

Currently, the more mainstream one is the CollectionUtils tool class under the org.apache.commons.collections package in apache.

<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.2</version>
</dependency>

It provides many methods. For example:

Of course, there is also the CollectionUtils tool class under the org.springframework.util package in the Spring framework.

However, I personally recommend using the CollectionUtils tool class under the apache package because it has more and more comprehensive tools. For a simple example, the CollectionUtils tool class in Spring does not have a method to determine if a collection is not empty. However, the CollectionUtils tool class in apache does.

Next, we will take the CollectionUtils tool class in apache as an example to introduce some commonly used methods.

The isEmpty method of the CollectionUtils tool class can easily determine if a collection is empty, and the isNotEmpty method determines if a collection is not empty.

List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);

if (CollectionUtils.isEmpty(list)) {
System.out.println("Collection is empty.");
}

if (CollectionUtils.isNotEmpty(list)) {
System.out.println("Collection is not empty");
}

Sometimes we need to operate on two existing collections, such as taking the intersection or union.

List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);

List<Integer> list2 = new ArrayList<>();
list2.add(2);
list2.add(4);

//Get Concatenation
Collection<Integer> unionList = CollectionUtils.union(list, list2);
System.out.println(unionList);

//Get Intersection
Collection<Integer> intersectionList = CollectionUtils.intersection(list, list2);
System.out.println(intersectionList);

//Get the complement of the intersection
Collection<Integer> disjunctionList = CollectionUtils.disjunction(list, list2);
System.out.println(disjunctionList);

//Get the difference set
Collection<Integer> subtractList = CollectionUtils.subtract(list, list2);
System.out.println(subtractList);

Execution result:

[1, 2, 3, 4]
[2]
[1, 3, 4]
[1, 3]

Operations on two collections are widely used in actual work. But when you have an idea for an operation, you can first try to check if there are existing tools available to avoid wasting time on it. Generally, some basic functions have already been implemented.

3. Lists

If you introduce the dependency of com.google.guava, you will get many useful small tools. Here is a collection tool under the com.google.common.collect package that is recommended: Lists.

It is so useful that I can’t put it down.

<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.2-jre</version>
</dependency>

Sometimes, we want to initialize some elements in a collection. At this time, we can use the newArrayList method of Lists. For example:

List<Integer> list = Lists.newArrayList(1, 2, 3);

It is more convenient than directly creating a list and then adding elements one by one.

Execution result:

[1, 2, 3]

If you want to perform a Cartesian product on two collections, the cartesianProduct method of Lists can help you achieve it:

List<Integer> list1 = Lists.newArrayList(1, 2, 3);
List<Integer> list2 = Lists.newArrayList(4, 5);
List<List<Integer>> productList = Lists.cartesianProduct(list1, list2);
System.out.println(productList);

Execution result

[[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]

If you want to split a large collection into several small collections, you can use the partition method of Lists:

List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
List<List<Integer>> partitionList = Lists.partition(list, 2);
System.out.println(partitionList);

Execution result:

[[1, 2], [3, 4], [5]]

In this example, the list has 5 pieces of data. I divided the list collection into 3 pages with a size of 2, that is, it becomes 3 small collections.

This is one of my favorite methods and is often used in projects.

For example, there is a requirement: now there are 10,000 ids, and the batch user query interface needs to be called to find out the user data. But if you directly query 10,000 users, the single interface response time may be very slow.

If it is changed to batch processing and only 500 users are queried each time, and the interface is asynchronously called 20 times, there will be no problem of slow single interface response.

If we want to convert a certain collection into another interface, we can use the transform method of Lists. For example:

List<String> list = Lists.newArrayList("a","b","c");
List<String> transformList = Lists.transform(list, x -> x.toUpperCase());
System.out.println(transformList);

The lowercase letters are converted into uppercase letters.

[A, B, C]

Lists has a method reverse() for reversing the order. For example:

List<Integer> list = Lists.newArrayList(3, 1, 2, 5, 4);
List<Integer> reverseList = Lists.reverse(list);
System.out.println(reverseList);

Execution result:

[4, 5, 2, 1, 3]

Of course, Lists has other useful tools. I am just presenting a few examples here. Interested friends can study it carefully.

4. Objects

After jdk7, the Objects tool class is provided, and we can operate on objects through it.

In Java, everything is an object. Checking if an object is null can be said to be everywhere. The isNull method of Objects checks if an object is null, while the nonNull method checks if an object is not null. For example:

Integer i = new Integer(10);

if (Objects.isNull(i)) {
System.out.println("Object is null");
}
if (Objects.nonNull(i)) {
System.out.println("Object is not null");
}

If we want to throw a null pointer exception when an object is null, we can use the requireNonNull method of Objects. For example:

Integer i = new Integer(128);

Objects.requireNonNull(i);
Objects.requireNonNull(i, "Parameters cannot be null");
Objects.requireNonNull(i, () -> "Parameters cannot be null");

We often need to check if two objects are equal. Objects provides us with the equals method, which can be very conveniently implemented:

Integer i1 = new Integer(1);
Integer i2 = new Integer(1);

System.out.println(Objects.equals(i1, i2));

Execution result:

true

But there is a pit when using this method. For example, if the example is changed to:

Integer i = new Integer(1);
Long l = new Long(1);

System.out.println(Objects.equals(i, l));

Execution result:

false

Do you know why it outputs false? You can communicate in the comment area.

If you want to get the hashCode of a certain object, you can use the hashCode method of Objects. For example:

String str = new String("abc");
System.out.println(Objects.hashCode(str));

Execution result:

96354

The introduction to the content of Objects is here for now. Interested friends can take a look at more methods below.

5. StringUtils

Strings are used very, very frequently in our daily work.

In our code, we often need to check if a string is null, convert case, split strings, compare strings, remove extra spaces, concatenate strings, use regular expressions, and so on.

If we only use the methods provided by the String class, we need to write a large amount of additional code by hand, which is time-consuming and laborious.

As programmers, of course, we need to learn to be lazy 😊. Now there is a ready-made tool class, the StringUtils tool class under the org.apache.commons.lang3 package, which provides us with a very rich selection.

In fact, for an empty string, there is not only null, but also “”, “ “, “null”, and many other situations.

StringUtils provides us with multiple static methods for checking if a string is null. For example:

String str1 = null;
String str2 = "";
String str3 = " ";
String str4 = "abc";
System.out.println(StringUtils.isEmpty(str1));
System.out.println(StringUtils.isEmpty(str2));
System.out.println(StringUtils.isEmpty(str3));
System.out.println(StringUtils.isEmpty(str4));
System.out.println("-------------------------------------");
System.out.println(StringUtils.isNotEmpty(str1));
System.out.println(StringUtils.isNotEmpty(str2));
System.out.println(StringUtils.isNotEmpty(str3));
System.out.println(StringUtils.isNotEmpty(str4));
System.out.println("-------------------------------------");
System.out.println(StringUtils.isBlank(str1));
System.out.println(StringUtils.isBlank(str2));
System.out.println(StringUtils.isBlank(str3));
System.out.println(StringUtils.isBlank(str4));
System.out.println("-------------------------------------");
System.out.println(StringUtils.isNotBlank(str1));
System.out.println(StringUtils.isNotBlank(str2));
System.out.println(StringUtils.isNotBlank(str3));
System.out.println(StringUtils.isNotBlank(str4));

Output:

true
true
false
false
-------------------------------------
false
false
true
true
-------------------------------------
true
true
true
false
-------------------------------------
false
false
false
true

The four null-checking methods in the example: isEmptyisNotEmptyisBlank, and isNotBlank. You can use these methods according to the actual situation.

It is recommended to use the isBlank and isNotBlank methods first, because they will also take " " into consideration.

Splitting strings is a common requirement. If you directly use the split method of the String class, a null pointer exception may occur.

String str1 = null;
System.out.println(StringUtils.split(str1, ","));
System.out.println(str1.split(","));

Output:

Using the split method of StringUtils will return null, while using the split method of String will report a pointer exception.

Given a string, to check if it is pure numbers, you can use the isNumeric method. For example:

String str1 = "123";
String str2 = "123abc";
String str3 = "0.33";
System.out.println(StringUtils.isNumeric(str1));
System.out.println(StringUtils.isNumeric(str2));
System.out.println(StringUtils.isNumeric(str3));

Output:

true
false
false

Sometimes, we need to concatenate the contents of a collection into a string and then output it. At this time, we can use the join method. For example:

List<String> list = Lists.newArrayList("a", "b", "c");
List<Integer> list2 = Lists.newArrayList(1, 2, 3);
System.out.println(StringUtils.join(list, ","));
System.out.println(StringUtils.join(list2, " "));

Output:

a,b,c
1 2 3

Of course, there are many practical methods. I won’t introduce them one by one here.

6. BeanUtils

Spring provides us with a tool class for JavaBean. It is under the org.springframework.beans package. Its name is: BeanUtils.

Let’s see what surprises this tool can bring us.

Have you encountered such a requirement: copy all the properties of a certain object to another object. At this time, you can use the copyProperties method of BeanUtils. For example:

User user1 = new User();
user1.setId(1L);
user1.setName("Dylan");
user1.setAddress("Hong Kong");

User user2 = new User();
BeanUtils.copyProperties(user1, user2);
System.out.println(user2);

If you want to get a specified method of a certain class for subsequent operations, you can use the findDeclaredMethod method of BeanUtils. For example:

Method declaredMethod = BeanUtils.findDeclaredMethod(User.class, "getId");
System.out.println(declaredMethod.getName());

If you want to get the parameters of a certain method, you can use the findPropertyForMethod method of BeanUtils. For example:

Method declaredMethod = BeanUtils.findDeclaredMethod(User.class, "getId");
PropertyDescriptor propertyForMethod = BeanUtils.findPropertyForMethod(declaredMethod);
System.out.println(propertyForMethod.getName());

If you are interested in BeanUtils, you can take a look at the following content:

7. ReflectionUtils

Sometimes, we need to use the reflection function in the project. If we use the most primitive method to develop, the amount of code will be very large and troublesome. It needs to handle a large number of exceptions and access permission issues.

The good news is that Spring provides us with a ReflectionUtils tool class, which is under the org.springframework.util package.

If you want to get a certain method of a certain class, you can use the findMethod method of the ReflectionUtils class. For example:

Method method = ReflectionUtils.findMethod(User.class, "getId");

If you want to get a certain field of a certain class, you can use the findField method of the ReflectionUtils class. For example:

Field field = ReflectionUtils.findField(User.class, "id");

If you want to call a certain method through reflection and pass parameters, you can use the invokeMethod method of the ReflectionUtils class. For example:

ReflectionUtils.invokeMethod(method, springContextsUtil.getBean(beanName), param);

If you want to check if a field is a constant, you can use the isPublicStaticFinal method of the ReflectionUtils class. For example:

Field field = ReflectionUtils.findField(User.class, "id");
System.out.println(ReflectionUtils.isPublicStaticFinal(field));

If you want to check if a certain method is an equals method, you can use the isEqualsMethod method of the ReflectionUtils class. For example:

Method method = ReflectionUtils.findMethod(User.class, "getId");
System.out.println(ReflectionUtils.isEqualsMethod(method));

Of course, this class still has many interesting methods. Interested friends can click into the class and take a look on their own.

8. DigestUtils

Sometimes, we need to encrypt data, such as using md5 or sha256.

We can use the DigestUtils class under the org.apache.commons.codec.digest package of Apache.

If you want to encrypt data using MD5, you can use the md5Hex method of DigestUtils. For example:

String md5Hex = DigestUtils.md5Hex("Dylan");
System.out.println(md5Hex);

If you want to encrypt data using SHA256, you can use the sha256Hex method of DigestUtils. For example:

String md5Hex = DigestUtils.sha256Hex("Dylan");
System.out.println(md5Hex);

Of course, this tool has many other encryption methods:

9. HttpStatus

Many times, we will define HTTP return codes in our code. For example, a normal interface returns 200, an abnormal return is 500, and if the interface cannot be found, it returns 404.

private int SUCCESS_CODE = 200;
private int ERROR_CODE = 500;
private int NOT_FOUND_CODE = 404;

In fact, the HttpStatus enumeration under the org.springframework.http package or the HttpStatus interface under the org.apache.http package has already defined the commonly used HTTP return codes for us. We can just use them directly and really don't need to redefine them.


Post a Comment

Previous Post Next Post