Boost Your Java Code with Essential Apache Commons & Guava Utilities
This article introduces a collection of practical Java utility classes—from Apache Commons StringUtils and DateUtils to Guava's Joiner and Stopwatch—showing how to simplify string handling, date conversion, collection checks, file I/O, and performance timing with concise code examples.
Recently a batch of interns joined the company, and the author mentored one who wrote solid code but sometimes duplicated logic that could be replaced with open‑source utility classes.
The author shares several commonly used tools to help newcomers avoid reinventing the wheel.
String‑related Utilities
Java's
Stringclass is used frequently, but its native API often requires multiple calls to achieve a business need. Apache Commons
StringUtilsprovides concise methods.
Maven dependency:
<code><dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
</code>commons‑lang has two versions: commons‑lang (old, no longer maintained) and commons‑lang3 (actively maintained). Use the latter.
Check if a String Is Empty
Traditional check:
<code>if (null == str || str.isEmpty()) {
// ...
}
</code>Using
StringUtils:
<code>if (StringUtils.isEmpty(str)) {
// ...
}
</code> StringUtils.isBlankalso exists; it returns
truefor strings containing only whitespace, unlike
isEmpty.
<code>// If the string consists solely of spaces
StringUtils.isBlank(" ") = true;
StringUtils.isEmpty(" ") = false;
</code>Fixed‑Length Strings
Pad a string to a fixed length (e.g., left‑pad with zeros):
<code>StringUtils.leftPad("test", 8, "0"); // "0000test"
</code>Right‑pad works similarly with
StringUtils.rightPad.
Keyword Replacement
<code>// Replace all occurrences
StringUtils.replace("aba", "a", "z") = "zbz";
// Replace only the first occurrence
StringUtils.replaceOnce("aba", "a", "z") = "zba";
// Replace using a regular expression
StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "") = "ABC123";
</code>String Concatenation
Using
StringBuildermanually can be error‑prone. Apache Commons offers a simpler way:
<code>StringUtils.join(new String[]{"a", "b", "c"}, ",") // "a,b,c"
</code>Guava’s
Joinerprovides additional flexibility, such as skipping nulls.
<code>Joiner onComma = Joiner.on(",").skipNulls();
joiner.join(array);
joiner.join(list);
</code>Date‑related Utilities
Before JDK 8,
java.util.Dateand
SimpleDateFormatwere the main tools, but
SimpleDateFormatis not thread‑safe. Apache Commons
DateUtilsand
DateFormatUtilssimplify conversion and calculation.
<code>// Format a Date to String
DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
// Parse a String to Date
DateUtils.parseDate("2020-05-07 22:00:00", "yyyy-MM-dd HH:mm:ss");
// Add/subtract time
Date addDays = DateUtils.addDays(now, 1);
Date addMinutes = DateUtils.addMinutes(now, 33);
Date addSeconds = DateUtils.addSeconds(now, -233);
boolean sameDay = DateUtils.isSameDay(addDays, addMinutes);
Date truncate = DateUtils.truncate(now, Calendar.DATE);
</code>JDK 8 introduced immutable, thread‑safe date‑time classes:
LocalDate,
LocalTime, and
LocalDateTime. Converting between
Dateand the new types requires specifying a time zone.
<code>LocalDateTime ldt = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
Date date = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
</code>Formatting with
LocalDateTime:
<code>LocalDateTime dateTime = LocalDateTime.parse("2020-05-07 22:34:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
String formatted = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dateTime);
</code>Collection/Array Utilities
Apache Commons Collections provides
CollectionUtilsand
MapUtilsfor null‑safe checks, while
ArrayUtils(from commons‑lang) handles array checks.
<code>if (CollectionUtils.isEmpty(list)) { /* ... */ }
if (MapUtils.isEmpty(map)) { /* ... */ }
if (ArrayUtils.isEmpty(array)) { /* ... */ }
</code>Adding an array to a collection:
<code>CollectionUtils.addAll(listA, arrays);
</code>Guava also offers
Listsand
Mapsfor similar operations.
I/O Utilities
Apache Commons IO’s
FileUtilssimplifies file copying, listing, reading, and writing.
<code>// Copy a file
FileUtils.copyFile(fileA, fileB);
// List files with specific extensions
FileUtils.listFiles(directory, new String[]{"txt"}, false);
// Read all lines
List<String> lines = FileUtils.readLines(fileA);
// Write lines
FileUtils.writeLines(fileB, lines);
</code>For stream handling,
IOUtilscan convert an
InputStreamto a byte array or a string in a single call.
<code>byte[] bytes = IOUtils.toByteArray(request.getInputStream());
String body = IOUtils.toString(request.getInputStream());
</code>Note: An InputStream can be read only once.
Timing Utilities
Guava’s
Stopwatchprovides flexible elapsed‑time measurement.
<code>Stopwatch sw = Stopwatch.createStarted();
TimeUnit.SECONDS.sleep(2);
System.out.println(sw.elapsed(TimeUnit.SECONDS)); // 2
TimeUnit.SECONDS.sleep(2);
System.out.println(sw.elapsed(TimeUnit.SECONDS)); // 4
sw.stop();
sw.start();
TimeUnit.SECONDS.sleep(2);
System.out.println(sw.elapsed(TimeUnit.SECONDS)); // 6
</code>Commons‑lang3 and Spring‑core also contain similar stopwatch utilities.
Conclusion
The author introduced a set of handy utility classes for strings, dates, collections, I/O, and timing, which can greatly simplify everyday Java development.
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.