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 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:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>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:
if (null == str || str.isEmpty()) {
// ...
}Using StringUtils:
if (StringUtils.isEmpty(str)) {
// ...
} StringUtils.isBlankalso exists; it returns true for strings containing only whitespace, unlike isEmpty.
// If the string consists solely of spaces
StringUtils.isBlank(" ") = true;
StringUtils.isEmpty(" ") = false;Fixed‑Length Strings
Pad a string to a fixed length (e.g., left‑pad with zeros):
StringUtils.leftPad("test", 8, "0"); // "0000test"Right‑pad works similarly with StringUtils.rightPad.
Keyword Replacement
// 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";String Concatenation
Using StringBuilder manually can be error‑prone. Apache Commons offers a simpler way:
StringUtils.join(new String[]{"a", "b", "c"}, ",") // "a,b,c"Guava’s Joiner provides additional flexibility, such as skipping nulls.
Joiner onComma = Joiner.on(",").skipNulls();
joiner.join(array);
joiner.join(list);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.
// 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);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.
LocalDateTime ldt = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
Date date = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());Formatting with LocalDateTime:
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);Collection/Array Utilities
Apache Commons Collections provides CollectionUtils and MapUtils for null‑safe checks, while ArrayUtils (from commons‑lang) handles array checks.
if (CollectionUtils.isEmpty(list)) { /* ... */ }
if (MapUtils.isEmpty(map)) { /* ... */ }
if (ArrayUtils.isEmpty(array)) { /* ... */ }Adding an array to a collection:
CollectionUtils.addAll(listA, arrays);Guava also offers Lists and Maps for similar operations.
I/O Utilities
Apache Commons IO’s FileUtils simplifies file copying, listing, reading, and writing.
// 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);For stream handling, IOUtils can convert an InputStream to a byte array or a string in a single call.
byte[] bytes = IOUtils.toByteArray(request.getInputStream());
String body = IOUtils.toString(request.getInputStream());Note: An InputStream can be read only once.
Timing Utilities
Guava’s Stopwatch provides flexible elapsed‑time measurement.
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)); // 6Commons‑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.
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.
