Unlock Java Power: 10 Must‑Know Guava Features for Cleaner Code

This guide introduces Google’s Guava library for Java, covering Maven integration, data validation with Preconditions, immutable collections, factory methods, counting collections, multimap usage, advanced string joining and splitting, and simple caching, showing how each feature can make code cleaner, safer, and more efficient.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
Unlock Java Power: 10 Must‑Know Guava Features for Cleaner Code
Recently I discovered extensive use of Google’s open‑source Guava core library in a colleague’s code, which made the code simpler and clearer, so I share the most useful Guava features.

Guava is Google’s open‑source Java core library providing utilities such as data validation, immutable collections, counting collections, enhanced collection operations, I/O, caching, and string handling. It is widely used inside Google and many other projects, and some classes have even been incorporated into newer JDK releases.

Dependency

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>30.0-jre</version>
</dependency>

Data Validation

Guava’s Preconditions simplifies null checks and argument validation.

Null check

String param = "example";
String name = Preconditions.checkNotNull(param);
String param2 = null;
String name2 = Preconditions.checkNotNull(param2, "param2 is null"); // throws NullPointerException with custom message

Argument check

String param = "www.wdbyte.com2";
String wdbyte = "www.wdbyte.com";
Preconditions.checkArgument(wdbyte.equals(param), "[%s] 404 NOT FOUND", param); // throws IllegalArgumentException

Index check

List<String> list = Lists.newArrayList("a","b","c","d");
int index = Preconditions.checkElementIndex(5, list.size()); // throws IndexOutOfBoundsException

Immutable Collections

Immutable collections cannot be modified, offering thread‑safety, safe sharing, reduced memory usage, and constant‑value semantics.

// of()
ImmutableSet<String> immutableSet = ImmutableSet.of("a","b","c");

// builder()
ImmutableSet<String> immutableSet2 = ImmutableSet.<String>builder()
    .add("hello")
    .add(new String("example"))
    .build();

// copyOf()
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("www.wdbyte.com");
arrayList.add("https");
ImmutableSet<String> immutableSet3 = ImmutableSet.copyOf(arrayList);

Attempting to modify an immutable collection throws UnsupportedOperationException. JDK also provides Collections.unmodifiableList, but Guava’s immutable collections reject null values and are truly immutable.

Collection Factories

List<String> list1 = Lists.newArrayList();
List<String> list2 = Lists.newArrayList("a","b","c");
List<String> list3 = Lists.newArrayListWithCapacity(10);
LinkedList<String> linkedList1 = Lists.newLinkedList();
CopyOnWriteArrayList<String> cowArrayList = Lists.newCopyOnWriteArrayList();

HashMap<Object,Object> hashMap = Maps.newHashMap();
ConcurrentMap<Object,Object> concurrentMap = Maps.newConcurrentMap();
TreeMap<Comparable,Object> treeMap = Maps.newTreeMap();

HashSet<Object> hashSet = Sets.newHashSet();
HashSet<String> newHashSet = Sets.newHashSet("a","a","b","c");

Counting Collections

// Using HashMultiset
ArrayList<String> arrayList = Lists.newArrayList("a","b","c","d","a","c");
HashMultiset<String> multiset = HashMultiset.create(arrayList);
multiset.elementSet().forEach(s -> System.out.println(s + ":" + multiset.count(s)));

Multimap (One‑to‑Many)

HashMultimap<String,String> multimap = HashMultimap.create();
multimap.put("dog","big yellow");
multimap.put("dog","wangcai");
multimap.put("cat","garfield");
multimap.put("cat","tom");
System.out.println(multimap.get("cat")); // [garfield, tom]

String Operations

Joining

ArrayList<String> list = Lists.newArrayList("a","b","c",null);
String join = Joiner.on(",").skipNulls().join(list); // a,b,c
String join1 = Joiner.on(",").useForNull("empty").join("wangcai","tom","jerry",null); // wangcai,tom,jerry,empty

Splitting

String str = ",a ,,b ,";
Iterable<String> split = Splitter.on(",")
    .omitEmptyStrings()
    .trimResults()
    .split(str);
split.forEach(System.out::println); // a b

Cache

@Test
public void testCache() throws ExecutionException, InterruptedException {
    CacheLoader<String, Animal> cacheLoader = new CacheLoader<String, Animal>() {
        @Override
        public Animal load(String s) {
            return null;
        }
    };
    LoadingCache<String, Animal> loadingCache = CacheBuilder.newBuilder()
        .maximumSize(1000)
        .expireAfterWrite(3, TimeUnit.SECONDS)
        .removalListener(new MyRemovalListener())
        .build(cacheLoader);
    loadingCache.put("dog", new Animal("wangcai",1));
    loadingCache.put("cat", new Animal("tom",3));
    loadingCache.put("wolf", new Animal("gray wolf",4));
    loadingCache.invalidate("cat");
    Animal animal = loadingCache.get("wolf");
    System.out.println(animal);
    Thread.sleep(4000);
    System.out.println(loadingCache.get("wolf"));
}
class MyRemovalListener implements RemovalListener<String, Animal> {
    @Override
    public void onRemoval(RemovalNotification<String, Animal> notification) {
        String reason = String.format("key=%s,value=%s,reason=%s",
                notification.getKey(), notification.getValue(), notification.getCause());
        System.out.println(reason);
    }
}
class Animal {
    private String name;
    private Integer age;
    @Override
    public String toString() {
        return "Animal{name='" + name + "', age=" + age + "}";
    }
    public Animal(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

Conclusion

Guava provides a rich set of utilities that simplify common Java tasks, make code more expressive, and improve safety. It is suitable for virtually any Java project, and many more features can be explored on its GitHub repository.

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.

JavaGuavaCollectionsdata validationString Utilities
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

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.