Master Google Guava: 40 Practical Examples to Supercharge Your Java Code

This article walks through the most commonly used Google Guava packages, demonstrating how to handle strings, collections, primitives, I/O, and various utility classes with concise code snippets and practical tips to boost Java development productivity.

Programmer1970
Programmer1970
Programmer1970
Master Google Guava: 40 Practical Examples to Supercharge Your Java Code

1. Guava Package Overview

Guava’s source packages cover a wide range of functionality. Key packages include:

com.google.common.base : core utilities such as Preconditions for argument validation and Optional for null‑safe handling.

com.google.common.collect : extended collection types like Multimap, Multiset, and many helper methods.

com.google.common.eventbus : a publish‑subscribe event bus for loosely coupled components.

com.google.common.hash : hashing utilities.

com.google.common.io : I/O helpers for file and stream operations.

com.google.common.math : arithmetic utilities for large numbers.

com.google.common.net : networking helpers such as URL handling.

com.google.common.primitives : static methods for primitive types.

com.google.common.reflect : reflection utilities.

com.google.common.util.concurrent : concurrency helpers including asynchronous computation and thread‑pool management.

2. String Handling Utilities

import com.google.common.base.CharMatcher;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.io.CharStreams;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

public class GuavaDemo {
    public static void main(String[] args) throws IOException {
        // 1. Joiner concatenates a list with ", "
        String joined = Joiner.on(", ").join("apple", "banana", "cherry");
        System.out.println(joined); // apple, banana, cherry

        // 2. Splitter splits the string and trims results
        Iterable<String> parts = Splitter.on(",").trimResults().split(joined);
        for (String s : parts) {
            System.out.println(s); // each element on a new line
        }

        // 3. Strings utilities for null/empty handling
        String nullStr = null;
        String emptyStr = "";
        String wsStr = "   ";
        System.out.println(Strings.nullToEmpty(nullStr)); // prints empty string
        System.out.println(Strings.isNullOrEmpty(emptyStr)); // true
        System.out.println(Strings.isNullOrEmpty(wsStr)); // false
        System.out.println(CharMatcher.whitespace().removeFrom(wsStr)); // empty string

        // 4. Charset handling and reading a resource file
        Charset utf8 = Charsets.UTF_8;
        try (InputStream in = GuavaDemo.class.getResourceAsStream("/test.txt");
             InputStreamReader reader = new InputStreamReader(in, utf8)) {
            String content = CharStreams.toString(reader);
            System.out.println(content); // prints file content assuming UTF‑8
        }

        // 5. CaseFormat conversion
        String camel = "ExampleClassName";
        String lower = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, camel);
        System.out.println(lower); // example_class_name
        String back = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, lower);
        System.out.println(back); // ExampleClassName

        // 6. CharMatcher examples
        String input = "Hello, World! This is a test string.";
        String noVowels = CharMatcher.is('a','e','i','o','u').removeFrom(input);
        System.out.println(noVowels); // Hll, Wrld! Ths s tst strng.
        String replaceVowels = CharMatcher.is('a','e','i','o','u').replaceFrom(input, '*');
        System.out.println(replaceVowels); // H*ll*, W*rld! Th*s *s * t*st str*ng.
        String keepVowels = CharMatcher.is('a','e','i','o','u').retainFrom(input);
        System.out.println(keepVowels); // eiooeiae

        // 7. CharSequences utilities
        int idx = CharSequences.indexOf(input, "test");
        System.out.println("Index: " + idx); // 21
        boolean eq = CharSequences.equals("Hello", "Hello");
        System.out.println("Equal: " + eq); // true
        String concat = CharSequences.concat("Guava ", "is ", "awesome!").toString();
        System.out.println(concat); // Guava is awesome!
    }
}

3. Primitive Type Utilities

import com.google.common.primitives.Booleans;
import com.google.common.primitives.Bytes;
import com.google.common.primitives.Chars;
import com.google.common.primitives.Doubles;
import com.google.common.primitives.Floats;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import com.google.common.primitives.Shorts;
import java.util.Arrays;

public class GuavaPrimitivesExample {
    public static void main(String[] args) {
        int[] intArr = {1,2,3,4,5};
        int sumInts = Ints.sum(intArr);
        System.out.println("Sum of ints: " + sumInts); // 15

        long[] longArr = {1L,2L,3L,4L,5L};
        long sumLongs = Longs.sum(longArr);
        System.out.println("Sum of longs: " + sumLongs); // 15

        double[] dblArr = {1.1,2.2,3.3,4.4,5.5};
        double sumDoubles = Doubles.sum(dblArr);
        System.out.println("Sum of doubles: " + sumDoubles); // 16.5

        float[] fltArr = {1.1f,2.2f,3.3f,4.4f,5.5f};
        float sumFloats = Floats.sum(fltArr);
        System.out.println("Sum of floats: " + sumFloats); // 16.5

        boolean[] boolArr = {true,false,true};
        boolean anyTrue = Booleans.contains(boolArr, true);
        System.out.println("Array contains true: " + anyTrue); // true

        byte[] byteArr = {1,2,3,4,5};
        byte minByte = Bytes.min(byteArr);
        System.out.println("Min byte: " + minByte); // 1

        short[] shortArr = {1,2,3,4,5};
        short maxShort = Shorts.max(shortArr);
        System.out.println("Max short: " + maxShort); // 5

        char[] charArr = {'a','b','c','d','e'};
        int countC = Chars.count(charArr, 'c');
        System.out.println("Count of 'c': " + countC); // 1

        int[] unsorted = {5,3,1,4,2};
        Arrays.sort(unsorted);
        System.out.println("Sorted int array: " + Arrays.toString(unsorted)); // [1,2,3,4,5]
    }
}

4. I/O Helper Classes

import com.google.common.base.Charsets;
import com.google.common.base.Supplier;
import com.google.common.io.ByteStreams;
import com.google.common.io.CharStreams;
import com.google.common.io.InputSupplier;
import com.google.common.io.OutputSupplier;
import com.google.common.io.Resources;
import java.io.*;
import java.net.URL;

public class GuavaIoExample {
    public static void main(String[] args) throws IOException {
        // InputSupplier example
        InputSupplier<InputStream> inSup = new InputSupplier<InputStream>() {
            @Override public InputStream getInput() throws IOException {
                return new ByteArrayInputStream("Hello, Guava!".getBytes(Charsets.UTF_8));
            }
        };
        String fromInSup = new String(ByteStreams.toByteArray(inSup.getInput()), Charsets.UTF_8);
        System.out.println("From InputSupplier: " + fromInSup);

        // OutputSupplier example
        OutputSupplier<OutputStream> outSup = new OutputSupplier<OutputStream>() {
            @Override public OutputStream getOutput() throws IOException {
                return new ByteArrayOutputStream();
            }
        };
        OutputStream out = outSup.getOutput();
        out.write("Hello, from OutputSupplier!".getBytes(Charsets.UTF_8));
        ((ByteArrayOutputStream) out).close();

        // Resources example
        URL url = Resources.getResource("somefile.txt");
        String fromRes = Resources.toString(url, Charsets.UTF_8);
        System.out.println("From Resources: " + fromRes);

        // ByteStreams copy example
        InputStream src = new ByteArrayInputStream("Data to copy".getBytes(Charsets.UTF_8));
        ByteArrayOutputStream dst = new ByteArrayOutputStream();
        ByteStreams.copy(src, dst);
        String copied = new String(dst.toByteArray(), Charsets.UTF_8);
        System.out.println("Copied Data: " + copied);

        // CharStreams read example
        Reader reader = new StringReader("Characters to read");
        String fromChar = CharStreams.toString(reader);
        System.out.println("From CharStreams: " + fromChar);

        // try‑with‑resources for safe closing
        try (StringWriter sw = new StringWriter()) {
            sw.write("Hello, try-with-resources!");
            String written = sw.toString();
            System.out.println("Written Data: " + written);
        }
    }
}

5. Miscellaneous Utilities

import com.google.common.base.Charsets;
import com.google.common.base.Throwables;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import com.google.common.io.BaseEncoding;
import com.google.common.io.ClassPath;
import com.google.common.util.concurrent.Uninterruptibles;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.TimeUnit;

public class GuavaUtilitiesExample {
    public static void main(String[] args) {
        // Stopwatch timing
        Stopwatch sw = Stopwatch.createStarted();
        Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
        long elapsed = sw.elapsed(TimeUnit.MILLISECONDS);
        System.out.println("Elapsed time: " + elapsed + " ms");

        // ClassPath scanning (caution: may be heavy)
        try {
            ClassPath cp = ClassPath.from(GuavaUtilitiesExample.class.getClassLoader());
            for (ClassPath.ClassInfo ci : cp.getAllClasses()) {
                if (ci.getName().contains("Guava")) {
                    System.out.println("Class found: " + ci.getName());
                }
            }
        } catch (IOException e) {
            Throwables.throwIfUnchecked(e);
        }

        // BaseEncoding (Base64) example
        String txt = "Hello, Guava!";
        String encoded = BaseEncoding.base64().encode(txt.getBytes(Charsets.UTF_8));
        byte[] decodedBytes = BaseEncoding.base64().decode(encoded);
        String decoded = new String(decodedBytes, Charsets.UTF_8);
        System.out.println("Original text: " + txt);
        System.out.println("Encoded text: " + encoded);
        System.out.println("Decoded text: " + decoded);

        // Throwables root cause example
        try {
            throw new RuntimeException("Outer exception", new IOException("Inner exception"));
        } catch (Exception e) {
            Throwable root = Throwables.getRootCause(e);
            System.out.println("Root cause: " + root.getMessage());
        }

        // HashCode (SHA‑256) example
        String toHash = "This is some text to hash";
        HashCode hc = Hashing.sha256().hashString(toHash, Charsets.UTF_8);
        System.out.println("SHA-256 hash: " + hc);
    }
}

ClassPath scans all classes on the class loader; use cautiously to avoid performance impact.

BaseEncoding provides convenient Base64 encoding/decoding.

Throwables helps retrieve the root cause of nested exceptions.

HashCode represents hash values (e.g., SHA‑256) distinct from Objects.hash().

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaconcurrencyHashingIOPrimitivesString handlingGoogle GuavaGuava utilities
Programmer1970
Written by

Programmer1970

Formerly called 'Code to 35'. Add our main WeChat ID to access a wealth of shared resources (algorithms, interview prep, tech stacks: Java, Python, Go, big data). We mainly share serious development techniques, focusing on output-driven input. Occasionally we post life snippets and gossip. Our aim is to attract precise traffic and test advertising opportunities.

0 followers
Reader feedback

How this landed with the community

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.