Backend Development 16 min read

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.

macrozheng
macrozheng
macrozheng
Boost Your Java Code with Essential Apache Commons & Guava Utilities

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

String

class is used frequently, but its native API often requires multiple calls to achieve a business need. Apache Commons

StringUtils

provides concise methods.

Maven dependency:

<code>&lt;dependency&gt;
    &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;
    &lt;artifactId&gt;commons-lang3&lt;/artifactId&gt;
    &lt;version&gt;3.10&lt;/version&gt;
&lt;/dependency&gt;
</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.isBlank

also exists; it returns

true

for 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

StringBuilder

manually can be error‑prone. Apache Commons offers a simpler way:

<code>StringUtils.join(new String[]{"a", "b", "c"}, ",") // "a,b,c"
</code>

Guava’s

Joiner

provides 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.Date

and

SimpleDateFormat

were the main tools, but

SimpleDateFormat

is not thread‑safe. Apache Commons

DateUtils

and

DateFormatUtils

simplify 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

Date

and 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

CollectionUtils

and

MapUtils

for 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

Lists

and

Maps

for similar operations.

I/O Utilities

Apache Commons IO’s

FileUtils

simplifies 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,

IOUtils

can convert an

InputStream

to 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

Stopwatch

provides 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.

JavaGuavaApache CommonsStringUtilsUtility ClassesDateUtils
macrozheng
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.