Comprehensive Java library providing essential utilities, immutable collections, caching, and concurrency tools for modern Java development.
—
Essential utilities for common programming tasks including string manipulation, preconditions, null handling, and functional programming support.
Annotations for API compatibility, testing visibility, and platform compatibility.
import com.google.common.annotations.*;
// Beta API annotation - indicates subject to incompatible changes
@Beta
public class ExperimentalFeature {
// This class might change in future releases
}
// GWT compatibility annotations
@GwtCompatible(serializable = true, emulated = true)
public class SerializableUtility {
// Compatible with Google Web Toolkit
}
@GwtIncompatible("Uses reflection not supported in GWT")
public class ReflectionUtility {
// Cannot be used with GWT
}
// Kotlin transpilation compatibility
@J2ktIncompatible("Uses Java-specific features")
public class JavaOnlyUtility {
// Cannot be used with J2kt (Kotlin transpilation)
}
// Testing visibility
public class InternalService {
@VisibleForTesting
protected void resetInternalState() {
// This method is only visible for testing purposes
// Would normally be private
}
}Key Annotations:
@Beta - Signifies that a public API is subject to incompatible changes or removal in future releases@GwtCompatible - Indicates that a type may be used with Google Web Toolkit (GWT)
serializable() - indicates if type is GWT serializableemulated() - indicates if type is emulated in GWT@GwtIncompatible - Indicates that an API may not be used with Google Web Toolkit (GWT)
value() - optional description of why element is incompatible@J2ktIncompatible - Indicates that an API may not be used with J2kt (Kotlin transpilation)@VisibleForTesting - Annotates elements that exist or are more visible than necessary only for test codeStatic convenience methods for checking method preconditions, arguments, and object state.
import com.google.common.base.Preconditions;
// Argument validation
public void setAge(int age) {
Preconditions.checkArgument(age >= 0, "Age must be non-negative: %s", age);
this.age = age;
}
// State validation
public void withdraw(double amount) {
Preconditions.checkState(isOpen(), "Account is closed");
Preconditions.checkArgument(amount > 0, "Amount must be positive");
this.balance -= amount;
}
// Null checking
public void setName(String name) {
this.name = Preconditions.checkNotNull(name, "Name cannot be null");
}
// Index validation
public T get(int index) {
Preconditions.checkElementIndex(index, size(), "Index out of bounds");
return elements[index];
}
// Range validation
public List<T> subList(int start, int end) {
Preconditions.checkPositionIndexes(start, end, size());
return new SubList(start, end);
}Key Methods:
checkArgument(boolean, String, Object...) - Validates method argumentscheckState(boolean, String, Object...) - Validates object statecheckNotNull(T, String, Object...) - Validates non-null referencescheckElementIndex(int, int, String) - Validates array/list element indexescheckPositionIndex(int, int, String) - Validates array/list position indexescheckPositionIndexes(int, int, int) - Validates start/end index rangesStatic utility methods for working with String instances, including null-safe operations and common string manipulations.
import com.google.common.base.Strings;
// Null safety
String safe = Strings.nullToEmpty(null); // ""
String nullable = Strings.emptyToNull(""); // null
boolean empty = Strings.isNullOrEmpty(""); // true
boolean empty2 = Strings.isNullOrEmpty(null); // true
// Padding
String padded = Strings.padStart("42", 5, '0'); // "00042"
String right = Strings.padEnd("hello", 10, '!'); // "hello!!!!!"
// Repetition
String repeated = Strings.repeat("hi", 3); // "hihihi"
// Common prefixes and suffixes
String prefix = Strings.commonPrefix("foobar", "foobaz"); // "fooba"
String suffix = Strings.commonSuffix("foobar", "bazbar"); // "bar"Key Methods:
nullToEmpty(String) - Returns empty string for null inputemptyToNull(String) - Returns null for empty string inputisNullOrEmpty(String) - Checks if string is null or emptypadStart(String, int, char) - Pads string at beginningpadEnd(String, int, char) - Pads string at endrepeat(String, int) - Repeats string specified number of timescommonPrefix(String, String) - Finds longest common prefixcommonSuffix(String, String) - Finds longest common suffixJoins pieces of text (arrays, Iterables, varargs) with a separator, with options for handling nulls.
import com.google.common.base.Joiner;
// Basic joining
Joiner joiner = Joiner.on(", ");
String result = joiner.join("a", "b", "c"); // "a, b, c"
// Joining collections
List<String> list = Arrays.asList("apple", "banana", "cherry");
String fruits = joiner.join(list); // "apple, banana, cherry"
// Handling nulls - skip them
String withNulls = Joiner.on(", ").skipNulls().join("a", null, "b", "c"); // "a, b, c"
// Handling nulls - substitute
String substituted = Joiner.on(", ").useForNull("missing").join("a", null, "b"); // "a, missing, b"
// Map joining
Map<String, String> map = ImmutableMap.of("key1", "value1", "key2", "value2");
String mapString = Joiner.on(", ").withKeyValueSeparator("=").join(map); // "key1=value1, key2=value2"Key Methods:
on(String) - Creates Joiner with separatorjoin(Object...) - Joins varargs elementsjoin(Iterable<?>) - Joins iterable elementsjoin(Iterator<?>) - Joins iterator elementsskipNulls() - Returns joiner that skips null elementsuseForNull(String) - Returns joiner that substitutes nulls with given stringwithKeyValueSeparator(String) - Returns MapJoiner for joining mapsSplits strings into parts using various delimiters and provides options for trimming and filtering results.
import com.google.common.base.Splitter;
// Basic splitting
Splitter splitter = Splitter.on(',');
List<String> parts = splitter.splitToList("a,b,c"); // ["a", "b", "c"]
// Character-based splitting
List<String> chars = Splitter.on(' ').splitToList("hello world"); // ["hello", "world"]
// Regular expression splitting
List<String> regex = Splitter.onPattern("\\s+").splitToList("a b c"); // ["a", "b", "c"]
// Trimming results
List<String> trimmed = Splitter.on(',')
.trimResults()
.splitToList("a, b , c "); // ["a", "b", "c"]
// Omitting empty strings
List<String> filtered = Splitter.on(',')
.omitEmptyStrings()
.splitToList("a,,b,"); // ["a", "b"]
// Limiting splits
List<String> limited = Splitter.on(',')
.limit(2)
.splitToList("a,b,c,d"); // ["a", "b,c,d"]
// Fixed-width splitting
List<String> fixedWidth = Splitter.fixedLength(3).splitToList("abcdef"); // ["abc", "def"]
// Key-value splitting
Map<String, String> keyValue = Splitter.on('&')
.withKeyValueSeparator('=')
.split("key1=value1&key2=value2"); // {key1=value1, key2=value2}Key Methods:
on(char) - Creates splitter on character delimiteron(String) - Creates splitter on string delimiteronPattern(String) - Creates splitter on regex patternfixedLength(int) - Creates splitter on fixed lengthsplitToList(CharSequence) - Splits to Listsplit(CharSequence) - Splits to IterabletrimResults() - Trims whitespace from resultsomitEmptyStrings() - Omits empty strings from resultslimit(int) - Limits number of splitswithKeyValueSeparator(char) - Creates MapSplitter for key-value pairsDetermines a true or false value for any Java char value and provides text processing methods based on character matching. Ideal for string cleaning, validation, and transformation.
import com.google.common.base.CharMatcher;
// Predefined matchers
CharMatcher digits = CharMatcher.digit();
CharMatcher letters = CharMatcher.javaLetter();
CharMatcher whitespace = CharMatcher.whitespace();
CharMatcher ascii = CharMatcher.ascii();
// Character-based text processing
String input = "Hello, World! 123";
// Remove unwanted characters
String lettersOnly = CharMatcher.javaLetter().retainFrom(input); // "HelloWorld"
String noDigits = CharMatcher.digit().removeFrom(input); // "Hello, World! "
// Replace characters
String cleaned = CharMatcher.whitespace().replaceFrom(input, '_'); // "Hello,_World!_123"
// Collapse consecutive characters
String collapsed = CharMatcher.whitespace()
.collapseFrom("a b c", ' '); // "a b c"
// Trim characters from ends
String trimmed = CharMatcher.whitespace().trimFrom(" hello "); // "hello"
// Check character patterns
boolean allAscii = CharMatcher.ascii().matchesAllOf(input);
boolean hasDigits = CharMatcher.digit().matchesAnyOf(input);
int digitCount = CharMatcher.digit().countIn(input); // 3
// Find positions
int firstDigit = CharMatcher.digit().indexIn(input); // 14
int lastDigit = CharMatcher.digit().lastIndexIn(input); // 16
// Custom matchers
CharMatcher vowels = CharMatcher.anyOf("aeiouAEIOU");
CharMatcher notVowels = vowels.negate();
CharMatcher consonants = CharMatcher.javaLetter().and(notVowels);
// Range-based matchers
CharMatcher numbers = CharMatcher.inRange('0', '9');
CharMatcher upperCase = CharMatcher.inRange('A', 'Z');
// Combining matchers
CharMatcher alphanumeric = CharMatcher.javaLetter().or(CharMatcher.digit());
CharMatcher specialChars = CharMatcher.ascii().and(alphanumeric.negate());Static Factory Methods:
any() - Matches any characternone() - Matches no characterswhitespace() - Matches whitespace charactersbreakingWhitespace() - Matches whitespace characters that break text linesascii() - Matches ASCII characters (0-127)digit() - Matches ASCII digits (0-9)javaDigit() - Matches characters for which Character.isDigit() returns truejavaLetter() - Matches characters for which Character.isLetter() returns truejavaLetterOrDigit() - Matches letters or digitsjavaUpperCase() - Matches uppercase charactersjavaLowerCase() - Matches lowercase charactersjavaIsoControl() - Matches ISO control charactersinvisible() - Matches invisible characters (whitespace, control chars, etc.)singleWidth() - Matches single-width characters (excludes double-width CJK)is(char) - Matches exactly one characterisNot(char) - Matches any character except the specified oneanyOf(CharSequence) - Matches any character in the sequencenoneOf(CharSequence) - Matches any character not in the sequenceinRange(char, char) - Matches characters in the inclusive rangeforPredicate(Predicate<Character>) - Matches characters accepted by predicateInstance Methods:
matches(char) - Tests if character matches this matchermatchesAnyOf(CharSequence) - Tests if any character in sequence matchesmatchesAllOf(CharSequence) - Tests if all characters in sequence matchmatchesNoneOf(CharSequence) - Tests if no characters in sequence matchindexIn(CharSequence) / indexIn(CharSequence, int) - First match indexlastIndexIn(CharSequence) - Last match indexcountIn(CharSequence) - Count of matching charactersremoveFrom(CharSequence) - Remove matching charactersretainFrom(CharSequence) - Retain only matching charactersreplaceFrom(CharSequence, char) - Replace matching chars with characterreplaceFrom(CharSequence, CharSequence) - Replace matching chars with stringtrimFrom(CharSequence) - Trim matching characters from both endstrimLeadingFrom(CharSequence) - Trim matching characters from starttrimTrailingFrom(CharSequence) - Trim matching characters from endcollapseFrom(CharSequence, char) - Collapse consecutive matches to single chartrimAndCollapseFrom(CharSequence, char) - Trim then collapse matchesCombining Operations:
negate() - Returns matcher that matches opposite charactersand(CharMatcher) - Returns matcher that matches both matchersor(CharMatcher) - Returns matcher that matches either matcherprecomputed() - Returns optimized version for repeated useHelper methods for Object instances including equality, hashing, and string representation.
import com.google.common.base.Objects;
import com.google.common.base.MoreObjects;
// Null-safe equality
public boolean equals(Object obj) {
if (obj instanceof Person) {
Person other = (Person) obj;
return Objects.equal(this.name, other.name) &&
Objects.equal(this.age, other.age);
}
return false;
}
// Hash code generation
public int hashCode() {
return Objects.hashCode(name, age, address);
}
// String representation
public String toString() {
return MoreObjects.toStringHelper(this)
.add("name", name)
.add("age", age)
.omitNullValues()
.toString(); // "Person{name=John, age=30}"
}
// First non-null value
String name = MoreObjects.firstNonNull(primaryName, secondaryName, "Unknown");Objects Methods:
equal(Object, Object) - Null-safe equality comparisonhashCode(Object...) - Generates hash codes from multiple fieldstoStringHelper(Object) - Creates ToStringHelper for the objectMoreObjects Methods:
toStringHelper(Class) - Creates ToStringHelper for classtoStringHelper(String) - Creates ToStringHelper with custom class namefirstNonNull(T, T) - Returns first non-null argumentImmutable object that may contain a non-null reference (predecessor to java.util.Optional).
import com.google.common.base.Optional;
import com.google.common.base.Function;
// Creating Optional instances
Optional<String> present = Optional.of("hello");
Optional<String> absent = Optional.absent();
Optional<String> nullable = Optional.fromNullable(getString()); // null -> absent
// Checking presence
if (optional.isPresent()) {
String value = optional.get();
System.out.println(value);
}
// Providing defaults
String value = optional.or("default");
String lazy = optional.or(new Supplier<String>() {
public String get() { return computeDefault(); }
});
// Transformation
Optional<Integer> length = optional.transform(new Function<String, Integer>() {
public Integer apply(String input) {
return input.length();
}
});
// Converting to java.util.Optional (if needed)
java.util.Optional<String> javaOptional = optional.toJavaUtil();Key Methods:
absent() - Creates absent Optionalof(T) - Creates Optional with non-null valuefromNullable(T) - Creates Optional from nullable valueisPresent() - Tests if value is presentget() - Gets the value (throws if absent)or(T) - Returns value or provided defaultor(Supplier<T>) - Returns value or supplier resultorNull() - Returns value or nulltransform(Function<T, V>) - Transforms value if presentCore functional interfaces for composing operations (note: prefer java.util.function interfaces in Java 8+).
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
// Function - transforms input to output
Function<String, Integer> length = new Function<String, Integer>() {
public Integer apply(String input) {
return input.length();
}
};
// Predicate - tests input for boolean property
Predicate<String> notEmpty = new Predicate<String>() {
public boolean apply(String input) {
return !input.isEmpty();
}
};
// Supplier - provides instances on demand
Supplier<String> timestamp = new Supplier<String>() {
public String get() {
return new Date().toString();
}
};Static utility methods for creating and composing functional interfaces.
import com.google.common.base.Functions;
import com.google.common.base.Predicates;
import com.google.common.base.Suppliers;
// Function utilities
Function<Object, String> toString = Functions.toStringFunction();
Function<String, String> identity = Functions.identity();
Function<String, Integer> composed = Functions.compose(length, toUpperCase);
Function<String, String> constant = Functions.constant("default");
Map<String, Integer> map = ImmutableMap.of("a", 1, "b", 2);
Function<String, Integer> mapLookup = Functions.forMap(map, 0); // default value 0
// Predicate utilities
Predicate<Object> alwaysTrue = Predicates.alwaysTrue();
Predicate<Object> alwaysFalse = Predicates.alwaysFalse();
Predicate<Object> isNull = Predicates.isNull();
Predicate<Object> notNull = Predicates.notNull();
Predicate<String> combined = Predicates.and(notEmpty, longerThan5);
Predicate<String> either = Predicates.or(isEmpty, startsWithA);
Predicate<String> negated = Predicates.not(isEmpty);
// Supplier utilities
Supplier<String> constant = Suppliers.ofInstance("constant value");
Supplier<String> memoized = Suppliers.memoize(expensiveComputation);
Supplier<String> withTimeout = Suppliers.memoizeWithExpiration(
computation, 10, TimeUnit.MINUTES);Static utility methods for working with exceptions and stack traces.
import com.google.common.base.Throwables;
try {
riskyOperation();
} catch (Exception e) {
// Propagate specific exception types
Throwables.throwIfInstanceOf(e, IOException.class);
Throwables.throwIfUnchecked(e);
// Or wrap in RuntimeException
throw new RuntimeException(e);
}
// Exception analysis
Throwable root = Throwables.getRootCause(exception);
List<Throwable> chain = Throwables.getCausalChain(exception);
String stackTrace = Throwables.getStackTraceAsString(exception);Key Methods:
throwIfInstanceOf(Throwable, Class<X>) - Propagates if exception is instance of typethrowIfUnchecked(Throwable) - Propagates if exception is RuntimeException or ErrorgetRootCause(Throwable) - Gets the root cause of exception chaingetCausalChain(Throwable) - Gets list of causes from exception to rootgetStackTraceAsString(Throwable) - Converts stack trace to stringAdditional utilities for common programming tasks.
import com.google.common.base.Verify;
import com.google.common.base.Stopwatch;
import com.google.common.base.Charsets;
import java.util.concurrent.TimeUnit;
// Verification (similar to Preconditions but throws VerifyException)
public void processResults(List<String> results) {
Verify.verify(!results.isEmpty(), "Results cannot be empty");
Verify.verifyNotNull(results.get(0), "First result cannot be null");
}
// Timing operations
Stopwatch stopwatch = Stopwatch.createStarted();
doWork();
long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
System.out.println("Work took: " + stopwatch);
// Standard charsets (prefer java.nio.charset.StandardCharsets in Java 7+)
Charset utf8 = Charsets.UTF_8;
Charset ascii = Charsets.US_ASCII;
// Case format conversion
import com.google.common.base.CaseFormat;
String camelCase = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "hello_world"); // "helloWorld"
String constantCase = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, "helloWorld"); // "HELLO_WORLD"Additional Classes:
Verify - Similar to Preconditions but throws VerifyException for internal invariantsStopwatch - Measures elapsed time with nanosecond precisionCaseFormat - Converts between ASCII case formats (camelCase, snake_case, etc.)Charsets - Standard charset constants (prefer java.nio.charset.StandardCharsets)Ascii - Utilities for ASCII character operationsDefaults - Default values for primitive and reference typesAdditional utility classes for specialized operations.
import com.google.common.base.Converter;
import com.google.common.base.Equivalence;
import com.google.common.base.Ticker;
import com.google.common.base.StandardSystemProperty;
import com.google.common.base.Defaults;
import com.google.common.base.Enums;
// Bidirectional conversion between types
public abstract class Converter<A, B> {
// Convert A to B
protected abstract B doForward(A a);
// Convert B to A
protected abstract A doBackward(B b);
// Public conversion method
public final B convert(A a) {
return doForward(a);
}
// Get reverse converter
public Converter<B, A> reverse() {
return new ReverseConverter<>(this);
}
}
// Example: String to Integer converter
Converter<String, Integer> stringToInt = new Converter<String, Integer>() {
@Override
protected Integer doForward(String str) {
return Integer.valueOf(str);
}
@Override
protected String doBackward(Integer integer) {
return integer.toString();
}
};
// Equivalence strategy (alternative to equals/hashCode)
Equivalence<String> caseInsensitive = new Equivalence<String>() {
@Override
protected boolean doEquivalent(String a, String b) {
return a.equalsIgnoreCase(b);
}
@Override
protected int doHash(String s) {
return s.toLowerCase().hashCode();
}
};
// System properties with null-safe access
String javaVersion = StandardSystemProperty.JAVA_VERSION.value();
String javaHome = StandardSystemProperty.JAVA_HOME.value();
String osName = StandardSystemProperty.OS_NAME.value();
// Default values for types
Object defaultObject = Defaults.defaultValue(Object.class); // null
int defaultInt = Defaults.defaultValue(int.class); // 0
boolean defaultBoolean = Defaults.defaultValue(boolean.class); // false
// Enum utilities
Optional<DayOfWeek> day = Enums.getIfPresent(DayOfWeek.class, "MONDAY");
Converter<String, DayOfWeek> dayConverter = Enums.stringConverter(DayOfWeek.class);
// Time source abstraction
public abstract class Ticker {
public abstract long read(); // Current time in nanoseconds
public static Ticker systemTicker() {
return SYSTEM_TICKER;
}
}Advanced Classes:
Converter<A,B> - Abstract class for bidirectional conversion between types A and BEquivalence<T> - Strategy for determining equivalence between instances (alternative to equals/hashCode)Ticker - Abstract source of nanosecond-precision time valuesStandardSystemProperty - Enum providing null-safe access to standard system propertiesDefaults - Utility for getting default values of primitive and reference typesEnums - Utility methods for working with Enum instancesInstall with Tessl CLI
npx tessl i tessl/maven-com-google-guava--guava