CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-google-guava--guava

Comprehensive Java library providing essential utilities, immutable collections, caching, and concurrency tools for modern Java development.

Pending
Overview
Eval results
Files

basic-utilities.mddocs/

Basic Utilities

Essential utilities for common programming tasks including string manipulation, preconditions, null handling, and functional programming support.

Package: com.google.common.annotations

Annotation Types

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 serializable
    • emulated() - 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 code

Package: com.google.common.base

Preconditions

Static 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 arguments
  • checkState(boolean, String, Object...) - Validates object state
  • checkNotNull(T, String, Object...) - Validates non-null references
  • checkElementIndex(int, int, String) - Validates array/list element indexes
  • checkPositionIndex(int, int, String) - Validates array/list position indexes
  • checkPositionIndexes(int, int, int) - Validates start/end index ranges

Strings

Static 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 input
  • emptyToNull(String) - Returns null for empty string input
  • isNullOrEmpty(String) - Checks if string is null or empty
  • padStart(String, int, char) - Pads string at beginning
  • padEnd(String, int, char) - Pads string at end
  • repeat(String, int) - Repeats string specified number of times
  • commonPrefix(String, String) - Finds longest common prefix
  • commonSuffix(String, String) - Finds longest common suffix

Joiner

Joins 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 separator
  • join(Object...) - Joins varargs elements
  • join(Iterable<?>) - Joins iterable elements
  • join(Iterator<?>) - Joins iterator elements
  • skipNulls() - Returns joiner that skips null elements
  • useForNull(String) - Returns joiner that substitutes nulls with given string
  • withKeyValueSeparator(String) - Returns MapJoiner for joining maps

Splitter

Splits 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 delimiter
  • on(String) - Creates splitter on string delimiter
  • onPattern(String) - Creates splitter on regex pattern
  • fixedLength(int) - Creates splitter on fixed length
  • splitToList(CharSequence) - Splits to List
  • split(CharSequence) - Splits to Iterable
  • trimResults() - Trims whitespace from results
  • omitEmptyStrings() - Omits empty strings from results
  • limit(int) - Limits number of splits
  • withKeyValueSeparator(char) - Creates MapSplitter for key-value pairs

CharMatcher

Determines 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 character
  • none() - Matches no characters
  • whitespace() - Matches whitespace characters
  • breakingWhitespace() - Matches whitespace characters that break text lines
  • ascii() - Matches ASCII characters (0-127)
  • digit() - Matches ASCII digits (0-9)
  • javaDigit() - Matches characters for which Character.isDigit() returns true
  • javaLetter() - Matches characters for which Character.isLetter() returns true
  • javaLetterOrDigit() - Matches letters or digits
  • javaUpperCase() - Matches uppercase characters
  • javaLowerCase() - Matches lowercase characters
  • javaIsoControl() - Matches ISO control characters
  • invisible() - Matches invisible characters (whitespace, control chars, etc.)
  • singleWidth() - Matches single-width characters (excludes double-width CJK)
  • is(char) - Matches exactly one character
  • isNot(char) - Matches any character except the specified one
  • anyOf(CharSequence) - Matches any character in the sequence
  • noneOf(CharSequence) - Matches any character not in the sequence
  • inRange(char, char) - Matches characters in the inclusive range
  • forPredicate(Predicate<Character>) - Matches characters accepted by predicate

Instance Methods:

  • matches(char) - Tests if character matches this matcher
  • matchesAnyOf(CharSequence) - Tests if any character in sequence matches
  • matchesAllOf(CharSequence) - Tests if all characters in sequence match
  • matchesNoneOf(CharSequence) - Tests if no characters in sequence match
  • indexIn(CharSequence) / indexIn(CharSequence, int) - First match index
  • lastIndexIn(CharSequence) - Last match index
  • countIn(CharSequence) - Count of matching characters
  • removeFrom(CharSequence) - Remove matching characters
  • retainFrom(CharSequence) - Retain only matching characters
  • replaceFrom(CharSequence, char) - Replace matching chars with character
  • replaceFrom(CharSequence, CharSequence) - Replace matching chars with string
  • trimFrom(CharSequence) - Trim matching characters from both ends
  • trimLeadingFrom(CharSequence) - Trim matching characters from start
  • trimTrailingFrom(CharSequence) - Trim matching characters from end
  • collapseFrom(CharSequence, char) - Collapse consecutive matches to single char
  • trimAndCollapseFrom(CharSequence, char) - Trim then collapse matches

Combining Operations:

  • negate() - Returns matcher that matches opposite characters
  • and(CharMatcher) - Returns matcher that matches both matchers
  • or(CharMatcher) - Returns matcher that matches either matcher
  • precomputed() - Returns optimized version for repeated use

Objects and MoreObjects

Helper 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 comparison
  • hashCode(Object...) - Generates hash codes from multiple fields
  • toStringHelper(Object) - Creates ToStringHelper for the object

MoreObjects Methods:

  • toStringHelper(Class) - Creates ToStringHelper for class
  • toStringHelper(String) - Creates ToStringHelper with custom class name
  • firstNonNull(T, T) - Returns first non-null argument

Optional

Immutable 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 Optional
  • of(T) - Creates Optional with non-null value
  • fromNullable(T) - Creates Optional from nullable value
  • isPresent() - Tests if value is present
  • get() - Gets the value (throws if absent)
  • or(T) - Returns value or provided default
  • or(Supplier<T>) - Returns value or supplier result
  • orNull() - Returns value or null
  • transform(Function<T, V>) - Transforms value if present

Functional Interfaces

Core 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();
    }
};

Utility Classes for Functional Interfaces

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);

Exception Utilities

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 type
  • throwIfUnchecked(Throwable) - Propagates if exception is RuntimeException or Error
  • getRootCause(Throwable) - Gets the root cause of exception chain
  • getCausalChain(Throwable) - Gets list of causes from exception to root
  • getStackTraceAsString(Throwable) - Converts stack trace to string

Other Utilities

Additional 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 invariants
  • Stopwatch - Measures elapsed time with nanosecond precision
  • CaseFormat - Converts between ASCII case formats (camelCase, snake_case, etc.)
  • Charsets - Standard charset constants (prefer java.nio.charset.StandardCharsets)
  • Ascii - Utilities for ASCII character operations
  • Defaults - Default values for primitive and reference types

Advanced Utilities

Additional 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 B
  • Equivalence<T> - Strategy for determining equivalence between instances (alternative to equals/hashCode)
  • Ticker - Abstract source of nanosecond-precision time values
  • StandardSystemProperty - Enum providing null-safe access to standard system properties
  • Defaults - Utility for getting default values of primitive and reference types
  • Enums - Utility methods for working with Enum instances

Install with Tessl CLI

npx tessl i tessl/maven-com-google-guava--guava

docs

basic-utilities.md

caching.md

collections.md

concurrency.md

graph-api.md

hash-math.md

immutable-collections.md

index.md

io-utilities.md

other-utilities.md

tile.json