How to Use Guava String Manipulation Utilities: Complete Guide to Strings, Joiner, and Splitter
Guava's string manipulation utilities provide null-safe, immutable helpers for padding, splitting, joining, and case conversion through the Strings, CharMatcher, Joiner, Splitter, and CaseFormat classes in com.google.common.base.
Working with text in Java often requires repetitive boilerplate for null checks, padding, and parsing. The Google Guava library eliminates this overhead through a comprehensive set of static utilities located in the com.google.common.base package. These Guava String manipulation utilities offer thread-safe, performant operations that handle edge cases like empty strings and whitespace without extra conditional logic.
Null-Safe String Handling with Strings
The Strings class in guava/src/com/google/common/base/Strings.java provides static methods for common null-safe operations, padding, and repetition. Unlike standard Java methods that throw NullPointerException on null inputs, these utilities accept nulls gracefully where appropriate.
Converting Null Values
Use nullToEmpty and emptyToNull to normalize strings between null and empty states without ternary operators.
String userInput = fetchValue(); // might return null
String safe = Strings.nullToEmpty(userInput); // returns "" if null
boolean isBlank = Strings.isNullOrEmpty(safe); // true for null or ""
Padding and Repeating Strings
The padStart and padEnd methods align text to specific widths, while repeat efficiently duplicates strings (a fallback for pre-Java 11 environments).
String id = "7";
String leftPadded = Strings.padStart(id, 3, '0'); // "007"
String rightPadded = Strings.padEnd(id, 5, '*'); // "7****"
String banner = Strings.repeat("abc", 3); // "abcabcabc"
Source: Strings.padStart, Strings.repeat
Finding Common Prefixes
The commonPrefix method compares two strings and returns the shared starting sequence, useful for path or identifier comparison.
String a = "interstellar";
String b = "internet";
String prefix = Strings.commonPrefix(a, b); // "inte"
Character Matching and Filtering with CharMatcher
CharMatcher in guava/src/com/google/common/base/CharMatcher.java offers fluent, predicate-style character processing. Instances are immutable and thread-safe, allowing you to store them as static final constants.
Trimming and Collapsing Whitespace
Use predefined matchers like whitespace() or ascii() to trim, remove, or collapse matching characters.
String messy = "\t Hello World \n";
// Trim whitespace from both ends
String trimmed = CharMatcher.whitespace().trimFrom(messy);
// "Hello World"
// Collapse multiple spaces into single spaces
String collapsed = CharMatcher.whitespace().collapseFrom(messy, ' ');
// " Hello World "
Removing Specific Characters
The removeFrom and retainFrom methods filter strings based on character predicates without regex overhead.
String alphanumeric = CharMatcher.inRange('0', '9').retainFrom("abc123xyz"); // "123"
String noDigits = CharMatcher.digit().removeFrom("abc123xyz"); // "abcxyz"
Concatenating Collections with Joiner
The Joiner class in guava/src/com/google/common/base/Joiner.java creates immutable, configurable string builders for concatenating arrays, Iterable objects, or Map entries. Unlike String.join(), it handles nulls explicitly through skipNulls() or useForNull(String).
Basic Joining with Null Handling
List<String> names = Arrays.asList("Harry", null, "Ron", "Hermione");
String result = Joiner.on("; ")
.skipNulls()
.join(names);
// "Harry; Ron; Hermione"
String withPlaceholders = Joiner.on(", ")
.useForNull("Unknown")
.join(names);
// "Harry, Unknown, Ron, Hermione"
Source: Joiner.on
Appending to Existing Buffers
The appendTo method writes directly to Appendable instances (like StringBuilder or Writer) without intermediate string creation.
StringBuilder sb = new StringBuilder("Names: ");
Joiner.on(" | ").appendTo(sb, "Alice", "Bob", "Carol");
// sb contains "Names: Alice | Bob | Carol"
Parsing Delimited Text with Splitter
Splitter in guava/src/com/google/common/base/Splitter.java provides a flexible alternative to String.split(). It returns a lazy Iterable<String> and supports trimming, empty string omission, and result limiting through an immutable builder pattern.
Configuring Split Behavior
Chain trimResults() and omitEmptyStrings() to clean data during parsing without post-processing loops.
String csv = "apple,,banana, ,cherry";
List<String> parts = Splitter.on(',')
.omitEmptyStrings()
.trimResults()
.splitToList(csv);
// ["apple", "banana", "cherry"]
Source: Splitter.on
Limiting Results
Use limit(int) to stop splitting after a specified number of tokens, preserving the remainder in the final element.
String input = "a,b,c,d,e";
List<String> limited = Splitter.on(',').limit(3).splitToList(input);
// ["a", "b", "c,d,e"]
Converting Naming Conventions with CaseFormat
The CaseFormat enum in guava/src/com/google/common/base/CaseFormat.java converts identifiers between common coding standards like lowerCamel, UPPER_UNDERSCORE, lower-hyphen, and UPPER_CAMEL.
String javaVariable = "myVariableName";
String constantName = CaseFormat.LOWER_CAMEL
.to(CaseFormat.UPPER_UNDERSCORE, javaVariable);
// "MY_VARIABLE_NAME"
String httpHeader = CaseFormat.UPPER_UNDERSCORE
.to(CaseFormat.LOWER_HYPHEN, "CONTENT_TYPE");
// "content-type"
Source: CaseFormat.to
Summary
- Strings (
com.google.common.base.Strings) provides null-safe conversions, padding viapadStart/padEnd, and efficient repetition withrepeat. - CharMatcher offers fluent character predicates for trimming, collapsing, and filtering without regex complexity.
- Joiner creates immutable delimited strings from collections while explicitly handling nulls through
skipNulls()oruseForNull(). - Splitter parses delimited text lazily with options to trim results, omit empties, and limit token counts.
- CaseFormat converts between identifier conventions (camelCase, snake_case, kebab-case) programmatically.
- All utilities are thread-safe and immutable; configure them once as
static finalconstants for reuse.
Frequently Asked Questions
What is the difference between Guava's Splitter and Java's String.split()?
Splitter returns a lazy Iterable<String> that processes the input sequentially without loading all results into memory immediately, whereas String.split() returns a String[] containing all elements upfront. Additionally, Splitter provides fluent configuration for trimming results, omitting empty strings, and limiting splits, while String.split() uses regular expressions which can be slower and require escaping for literal delimiters.
How does Guava handle null values in Joiner operations?
By default, Joiner throws a NullPointerException if it encounters a null element. You must explicitly configure null handling using either skipNulls() to ignore null elements entirely, or useForNull(String) to substitute a default string placeholder. This design forces developers to make conscious decisions about null data rather than silently accepting unexpected values.
Is CharMatcher thread-safe?
Yes, CharMatcher instances are immutable and thread-safe. All configuration methods like trimFrom, removeFrom, and collapseFrom return new strings or new matchers rather than modifying internal state. You can safely store CharMatcher constants as static final fields and share them across multiple threads without synchronization.
Which Guava utility should I use for zero-padding numeric strings?
Use Strings.padStart from the Strings class. This method accepts the target string, minimum length, and padding character, efficiently prepending characters until the desired length is reached. For example, Strings.padStart("7", 3, '0') produces "007", making it ideal for formatting IDs, timestamps, or fixed-width records.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →