Boost Java Productivity: 17 Essential Utility Classes Every Backend Developer Should Know
This article introduces 17 practical Java utility classes—including Collections, CollectionUtils, Lists, Objects, BooleanUtils, StringUtils, Assert, IOUtils, MDC, ClassUtils, BeanUtils, ReflectionUtils, Base64Utils, StandardCharsets, DigestUtils, SerializationUtils, and HttpStatus—showing how to use them with clear code examples to streamline everyday development tasks.
Preface
Java offers many handy utilities, often referred to as "wheels". By combining these utilities with IDE shortcuts, developers can dramatically improve productivity. This article shares 17 useful tools that can be applied in daily work.
1. Collections
The
java.util.Collectionsclass provides methods for operating on and returning collections.
1.1 Sorting
Sorting a list in ascending and descending order:
<code>List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
Collections.sort(list); // ascending
System.out.println(list);
Collections.reverse(list); // descending
System.out.println(list);
</code>Result:
<code>[1, 2, 3]
[3, 2, 1]
</code>1.2 Max/Min
Finding the maximum or minimum value in a collection:
<code>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);
</code>Result:
<code>3
1
</code>1.3 Thread‑Safe Collections
Convert a non‑thread‑safe collection to a synchronized version:
<code>List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
List<Integer> syncList = Collections.synchronizedList(list);
System.out.println(syncList);
</code>The underlying implementation creates
SynchronizedRandomAccessListor
SynchronizedList, which use
synchronizedlocks.
1.4 Empty Collections
Return an immutable empty list when a collection is null or empty:
<code>private List<Integer> fun(List<Integer> list) {
if (list == null || list.size() == 0) {
return Collections.emptyList();
}
// business logic
return list;
}
</code>1.5 Binary Search
Perform a binary search on a sorted list:
<code>List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
int i = Collections.binarySearch(list, 3); // binary search
System.out.println(i);
</code>Result:
<code>2
</code>1.6 Unmodifiable Collections
Create an immutable list that throws an exception on modification attempts:
<code>List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
List<Integer> unmod = Collections.unmodifiableList(list);
unmod.add(4); // throws UnsupportedOperationException
</code>Result:
<code>Exception in thread "main" java.lang.UnsupportedOperationException
</code>2. CollectionUtils
Beyond
Collections, the
CollectionUtilsclass from Spring (
org.springframework.util.CollectionUtils) and Apache Commons (
org.apache.commons.collections.CollectionUtils) provides additional utilities.
I personally recommend the Apache version because it offers more comprehensive methods.
2.1 Empty Check
Check if a collection is empty or not:
<code>if (CollectionUtils.isEmpty(list)) {
System.out.println("Collection is empty");
}
if (CollectionUtils.isNotEmpty(list)) {
System.out.println("Collection is not empty");
}
</code>2.2 Set Operations
Union, intersection, disjunction, and subtraction of two collections:
<code>Collection<Integer> union = CollectionUtils.union(list1, list2);
Collection<Integer> intersection = CollectionUtils.intersection(list1, list2);
Collection<Integer> disjunction = CollectionUtils.disjunction(list1, list2);
Collection<Integer> subtract = CollectionUtils.subtract(list1, list2);
System.out.println(union);
System.out.println(intersection);
System.out.println(disjunction);
System.out.println(subtract);
</code>Result:
<code>[1, 2, 3, 4]
[2]
[1, 3, 4]
[1, 3]
</code>3. Lists (Guava)
The Guava library (
com.google.common.collect.Lists) offers convenient list utilities.
3.1 Create Empty List
<code>List<Integer> list = Lists.newArrayList();
</code>3.2 Initialize List
<code>List<Integer> list = Lists.newArrayList(1, 2, 3);
System.out.println(list);
</code>Result:
<code>[1, 2, 3]
</code>3.3 Cartesian Product
<code>List<Integer> list1 = Lists.newArrayList(1, 2, 3);
List<Integer> list2 = Lists.newArrayList(4, 5);
List<List<Integer>> product = Lists.cartesianProduct(list1, list2);
System.out.println(product);
</code>Result:
<code>[[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
</code>3.4 Partition (Paging)
<code>List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
List<List<Integer>> pages = Lists.partition(list, 2);
System.out.println(pages);
</code>Result:
<code>[[1, 2], [3, 4], [5]]
</code>3.5 Transform (Stream‑like)
<code>List<String> list = Lists.newArrayList("a", "b", "c");
List<String> upper = Lists.transform(list, x -> x.toUpperCase());
System.out.println(upper);
</code>Result:
<code>[A, B, C]
</code>3.6 Reverse Order
<code>List<Integer> list = Lists.newArrayList(3, 1, 2);
List<Integer> reversed = Lists.reverse(list);
System.out.println(reversed);
</code>Result:
<code>[2, 1, 3]
</code>4. Objects (JDK 7+)
4.1 Null Check
<code>if (Objects.isNull(integer)) {
System.out.println("Object is null");
}
if (Objects.nonNull(integer)) {
System.out.println("Object is not null");
}
</code>4.2 Require Non‑Null
<code>Objects.requireNonNull(integer);
Objects.requireNonNull(integer, "Parameter cannot be null");
Objects.requireNonNull(integer, () -> "Parameter cannot be null");
</code>4.3 Equality Check
<code>System.out.println(Objects.equals(integer1, integer2));
</code>Result:
<code>true
</code>4.4 Hash Code
<code>System.out.println(Objects.hashCode(str));
</code>Result:
<code>96354
</code>5. BooleanUtils (Apache Commons)
5.1 isTrue / isFalse
<code>System.out.println(BooleanUtils.isTrue(aBoolean));
System.out.println(BooleanUtils.isFalse(aBoolean));
</code>5.2 isNotTrue / isNotFalse
<code>System.out.println(BooleanUtils.isNotTrue(aBoolean));
System.out.println(BooleanUtils.isNotTrue(aBoolean1));
System.out.println(BooleanUtils.isNotFalse(aBoolean));
System.out.println(BooleanUtils.isNotFalse(aBoolean1));
</code>Result:
<code>false
true
true
true
</code>5.3 toInteger
<code>System.out.println(BooleanUtils.toInteger(true));
System.out.println(BooleanUtils.toInteger(false));
</code>Result:
<code>1
0
</code>5.4 toBoolean / toBooleanDefaultIfNull
<code>System.out.println(BooleanUtils.toBoolean(aBoolean));
System.out.println(BooleanUtils.toBoolean(aBoolean1));
System.out.println(BooleanUtils.toBooleanDefaultIfNull(aBoolean1, false));
</code>Result:
<code>true
false
false
</code>6. StringUtils (Apache Commons Lang)
6.1 Empty / Blank Checks
<code>System.out.println(StringUtils.isEmpty(str1));
System.out.println(StringUtils.isBlank(str1));
System.out.println(StringUtils.isNotEmpty(str2));
System.out.println(StringUtils.isNotBlank(str2));
</code>6.2 Split
<code>System.out.println(StringUtils.split(null, ",")); // returns null
</code>6.3 isNumeric
<code>System.out.println(StringUtils.isNumeric("123"));
System.out.println(StringUtils.isNumeric("123q"));
System.out.println(StringUtils.isNumeric("0.33"));
</code>Result:
<code>true
false
false
</code>6.4 Join
<code>System.out.println(StringUtils.join(list, ","));
System.out.println(StringUtils.join(list2, " "));
</code>Result:
<code>a,b,c
1 2 3
</code>7. Assert (Spring)
7.1 Parameter Null Check
<code>Assert.isNull(str, "str must be null");
Assert.notNull(str, "str cannot be null");
</code>7.2 Collection Empty Check
<code>Assert.notEmpty(list, "list cannot be empty");
Assert.notEmpty(map, "map cannot be empty");
</code>7.3 Condition Check
<code>Assert.isTrue(CollectionUtils.isNotEmpty(list), "list cannot be empty");
</code>8. IOUtils (Apache Commons IO)
8.1 Read File to String
<code>String content = IOUtils.toString(new FileInputStream("/temp/a.txt"), StandardCharsets.UTF_8);
System.out.println(content);
</code>8.2 Write String to File
<code>IOUtils.write("abcde", new FileOutputStream("/temp/b.txt"), StandardCharsets.UTF_8);
</code>8.3 Copy File
<code>IOUtils.copy(new FileInputStream("/temp/a.txt"), new FileOutputStream("/temp/b.txt"));
</code>8.4 Read File to Byte Array
<code>byte[] bytes = IOUtils.toByteArray(new FileInputStream("/temp/a.txt"));
</code>9. MDC (SLF4J)
MDC provides a thread‑local map for diagnostic context, useful for passing trace IDs across service calls. Example code shows a servlet filter that adds a UUID to MDC and a
ClientHttpRequestInterceptorthat copies the trace ID into HTTP headers.
<code>public class LogFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
MdcUtil.add(UUID.randomUUID().toString());
chain.doFilter(request, response);
}
}
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) {
request.getHeaders().set("traceId", MdcUtil.get());
return execution.execute(request, body);
}
}
public class MdcUtil {
private static final String TRACE_ID = "TRACE_ID";
public static String get() { return MDC.get(TRACE_ID); }
public static void add(String value) { MDC.put(TRACE_ID, value); }
}
</code>10. ClassUtils (Spring)
10.1 Get All Interfaces
<code>Class<?>[] interfaces = ClassUtils.getAllInterfaces(new User());
</code>10.2 Get Package Name
<code>String pkg = ClassUtils.getPackageName(User.class);
</code>10.3 Is Inner Class
<code>System.out.println(ClassUtils.isInnerClass(User.class));
</code>10.4 Is CGLIB Proxy
<code>System.out.println(ClassUtils.isCglibProxy(new User()));
</code>11. BeanUtils (Spring)
11.1 Copy Properties
<code>User src = new User();
src.setId(1L);
src.setName("Example");
User dest = new User();
BeanUtils.copyProperties(src, dest);
</code>11.2 Instantiate Class
<code>User user = BeanUtils.instantiateClass(User.class);
</code>11.3 Find Declared Method
<code>Method m = BeanUtils.findDeclaredMethod(User.class, "getId");
</code>11.4 Find Property for Method
<code>PropertyDescriptor pd = BeanUtils.findPropertyForMethod(m);
</code>12. ReflectionUtils (Spring)
12.1 Find Method
<code>Method m = ReflectionUtils.findMethod(User.class, "getId");
</code>12.2 Find Field
<code>Field f = ReflectionUtils.findField(User.class, "id");
</code>12.3 Invoke Method
<code>ReflectionUtils.invokeMethod(m, beanInstance, param);
</code>12.4 Is Public Static Final
<code>System.out.println(ReflectionUtils.isPublicStaticFinal(f));
</code>12.5 Is Equals Method
<code>System.out.println(ReflectionUtils.isEqualsMethod(m));
</code>13. Base64Utils (Spring)
<code>String encoded = new String(Base64Utils.encode("abc".getBytes()));
String decoded = new String(Base64Utils.decode(encoded.getBytes()), "UTF-8");
System.out.println("Encoded: " + encoded);
System.out.println("Decoded: " + decoded);
</code>Result:
<code>Encoded: YWJj
Decoded: abc
</code>14. StandardCharsets (Java)
<code>String decoded = new String(Base64Utils.decode(encoded.getBytes()), StandardCharsets.UTF_8);
</code>15. DigestUtils (Apache Commons Codec)
15.1 MD5
<code>String md5 = DigestUtils.md5Hex("苏三说技术");
System.out.println(md5);
</code>15.2 SHA‑256
<code>String sha256 = DigestUtils.sha256Hex("苏三说技术");
System.out.println(sha256);
</code>16. SerializationUtils (Spring)
<code>Map<String, String> map = new HashMap<>();
map.put("a", "1");
byte[] data = SerializationUtils.serialize(map);
Object obj = SerializationUtils.deserialize(data);
System.out.println(obj);
</code>17. HttpStatus (Spring / Apache)
Instead of defining custom HTTP status constants, use the predefined enums in
org.springframework.http.HttpStatusor
org.apache.http.HttpStatusfor standard codes such as 200, 404, 500, etc.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.