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.Collections class provides methods for operating on and returning collections.
1.1 Sorting
Sorting a list in ascending and descending order:
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);Result:
[1, 2, 3]
[3, 2, 1]1.2 Max/Min
Finding the maximum or minimum value in a collection:
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);Result:
3
11.3 Thread‑Safe Collections
Convert a non‑thread‑safe collection to a synchronized version:
List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
List<Integer> syncList = Collections.synchronizedList(list);
System.out.println(syncList);The underlying implementation creates SynchronizedRandomAccessList or SynchronizedList, which use synchronized locks.
1.4 Empty Collections
Return an immutable empty list when a collection is null or empty:
private List<Integer> fun(List<Integer> list) {
if (list == null || list.size() == 0) {
return Collections.emptyList();
}
// business logic
return list;
}1.5 Binary Search
Perform a binary search on a sorted list:
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);Result:
21.6 Unmodifiable Collections
Create an immutable list that throws an exception on modification attempts:
List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
List<Integer> unmod = Collections.unmodifiableList(list);
unmod.add(4); // throws UnsupportedOperationExceptionResult:
Exception in thread "main" java.lang.UnsupportedOperationException2. CollectionUtils
Beyond Collections, the CollectionUtils class 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:
if (CollectionUtils.isEmpty(list)) {
System.out.println("Collection is empty");
}
if (CollectionUtils.isNotEmpty(list)) {
System.out.println("Collection is not empty");
}2.2 Set Operations
Union, intersection, disjunction, and subtraction of two collections:
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);Result:
[1, 2, 3, 4]
[2]
[1, 3, 4]
[1, 3]3. Lists (Guava)
The Guava library ( com.google.common.collect.Lists) offers convenient list utilities.
3.1 Create Empty List
List<Integer> list = Lists.newArrayList();3.2 Initialize List
List<Integer> list = Lists.newArrayList(1, 2, 3);
System.out.println(list);Result:
[1, 2, 3]3.3 Cartesian Product
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);Result:
[[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]3.4 Partition (Paging)
List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
List<List<Integer>> pages = Lists.partition(list, 2);
System.out.println(pages);Result:
[[1, 2], [3, 4], [5]]3.5 Transform (Stream‑like)
List<String> list = Lists.newArrayList("a", "b", "c");
List<String> upper = Lists.transform(list, x -> x.toUpperCase());
System.out.println(upper);Result:
[A, B, C]3.6 Reverse Order
List<Integer> list = Lists.newArrayList(3, 1, 2);
List<Integer> reversed = Lists.reverse(list);
System.out.println(reversed);Result:
[2, 1, 3]4. Objects (JDK 7+)
4.1 Null Check
if (Objects.isNull(integer)) {
System.out.println("Object is null");
}
if (Objects.nonNull(integer)) {
System.out.println("Object is not null");
}4.2 Require Non‑Null
Objects.requireNonNull(integer);
Objects.requireNonNull(integer, "Parameter cannot be null");
Objects.requireNonNull(integer, () -> "Parameter cannot be null");4.3 Equality Check
System.out.println(Objects.equals(integer1, integer2));Result:
true4.4 Hash Code
System.out.println(Objects.hashCode(str));Result:
963545. BooleanUtils (Apache Commons)
5.1 isTrue / isFalse
System.out.println(BooleanUtils.isTrue(aBoolean));
System.out.println(BooleanUtils.isFalse(aBoolean));5.2 isNotTrue / isNotFalse
System.out.println(BooleanUtils.isNotTrue(aBoolean));
System.out.println(BooleanUtils.isNotTrue(aBoolean1));
System.out.println(BooleanUtils.isNotFalse(aBoolean));
System.out.println(BooleanUtils.isNotFalse(aBoolean1));Result:
false
true
true
true5.3 toInteger
System.out.println(BooleanUtils.toInteger(true));
System.out.println(BooleanUtils.toInteger(false));Result:
1
05.4 toBoolean / toBooleanDefaultIfNull
System.out.println(BooleanUtils.toBoolean(aBoolean));
System.out.println(BooleanUtils.toBoolean(aBoolean1));
System.out.println(BooleanUtils.toBooleanDefaultIfNull(aBoolean1, false));Result:
true
false
false6. StringUtils (Apache Commons Lang)
6.1 Empty / Blank Checks
System.out.println(StringUtils.isEmpty(str1));
System.out.println(StringUtils.isBlank(str1));
System.out.println(StringUtils.isNotEmpty(str2));
System.out.println(StringUtils.isNotBlank(str2));6.2 Split
System.out.println(StringUtils.split(null, ",")); // returns null6.3 isNumeric
System.out.println(StringUtils.isNumeric("123"));
System.out.println(StringUtils.isNumeric("123q"));
System.out.println(StringUtils.isNumeric("0.33"));Result:
true
false
false6.4 Join
System.out.println(StringUtils.join(list, ","));
System.out.println(StringUtils.join(list2, " "));Result:
a,b,c
1 2 37. Assert (Spring)
7.1 Parameter Null Check
Assert.isNull(str, "str must be null");
Assert.notNull(str, "str cannot be null");7.2 Collection Empty Check
Assert.notEmpty(list, "list cannot be empty");
Assert.notEmpty(map, "map cannot be empty");7.3 Condition Check
Assert.isTrue(CollectionUtils.isNotEmpty(list), "list cannot be empty");8. IOUtils (Apache Commons IO)
8.1 Read File to String
String content = IOUtils.toString(new FileInputStream("/temp/a.txt"), StandardCharsets.UTF_8);
System.out.println(content);8.2 Write String to File
IOUtils.write("abcde", new FileOutputStream("/temp/b.txt"), StandardCharsets.UTF_8);8.3 Copy File
IOUtils.copy(new FileInputStream("/temp/a.txt"), new FileOutputStream("/temp/b.txt"));8.4 Read File to Byte Array
byte[] bytes = IOUtils.toByteArray(new FileInputStream("/temp/a.txt"));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 ClientHttpRequestInterceptor that copies the trace ID into HTTP headers.
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); }
}10. ClassUtils (Spring)
10.1 Get All Interfaces
Class<?>[] interfaces = ClassUtils.getAllInterfaces(new User());10.2 Get Package Name
String pkg = ClassUtils.getPackageName(User.class);10.3 Is Inner Class
System.out.println(ClassUtils.isInnerClass(User.class));10.4 Is CGLIB Proxy
System.out.println(ClassUtils.isCglibProxy(new User()));11. BeanUtils (Spring)
11.1 Copy Properties
User src = new User();
src.setId(1L);
src.setName("Example");
User dest = new User();
BeanUtils.copyProperties(src, dest);11.2 Instantiate Class
User user = BeanUtils.instantiateClass(User.class);11.3 Find Declared Method
Method m = BeanUtils.findDeclaredMethod(User.class, "getId");11.4 Find Property for Method
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(m);12. ReflectionUtils (Spring)
12.1 Find Method
Method m = ReflectionUtils.findMethod(User.class, "getId");12.2 Find Field
Field f = ReflectionUtils.findField(User.class, "id");12.3 Invoke Method
ReflectionUtils.invokeMethod(m, beanInstance, param);12.4 Is Public Static Final
System.out.println(ReflectionUtils.isPublicStaticFinal(f));12.5 Is Equals Method
System.out.println(ReflectionUtils.isEqualsMethod(m));13. Base64Utils (Spring)
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);Result:
Encoded: YWJj
Decoded: abc14. StandardCharsets (Java)
String decoded = new String(Base64Utils.decode(encoded.getBytes()), StandardCharsets.UTF_8);15. DigestUtils (Apache Commons Codec)
15.1 MD5
String md5 = DigestUtils.md5Hex("苏三说技术");
System.out.println(md5);15.2 SHA‑256
String sha256 = DigestUtils.sha256Hex("苏三说技术");
System.out.println(sha256);16. SerializationUtils (Spring)
Map<String, String> map = new HashMap<>();
map.put("a", "1");
byte[] data = SerializationUtils.serialize(map);
Object obj = SerializationUtils.deserialize(data);
System.out.println(obj);17. HttpStatus (Spring / Apache)
Instead of defining custom HTTP status constants, use the predefined enums in org.springframework.http.HttpStatus or org.apache.http.HttpStatus for standard codes such as 200, 404, 500, etc.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
