What is Guava?
Guava is an open-source Java library developed by Google. It provides a wide variety of core libraries that complement Java’s standard libraries. Guava focuses on making Java programming easier, safer, and more efficient.
Some key areas Guava helps with:
- Collections
- Caching
- Functional programming utilities
- String manipulation
- Concurrency utilities
- Hashing
- I/O utilities
1. Collections
Guava provides advanced collection types and utilities that Java doesn’t natively have.
Examples:
- Immutable collections
import com.google.common.collect.ImmutableList;
ImmutableList<String> list = ImmutableList.of("apple", "banana", "guava");
Immutable collections cannot be modified after creation, which helps prevent bugs.
- Multimap (a map that allows multiple values per key)
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
Multimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("fruit", "apple");
multimap.put("fruit", "banana");
System.out.println(multimap.get("fruit")); // [apple, banana]
- BiMap (a bidirectional map)
import com.google.common.collect.HashBiMap;
import com.google.common.collect.BiMap;
BiMap<Integer, String> userMap = HashBiMap.create();
userMap.put(1, "Alice");
userMap.put(2, "Bob");
System.out.println(userMap.inverse().get("Alice")); // 1
2. Caching
Guava provides an in-memory cache mechanism that’s thread-safe and easy to use.
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
Cache<String, Integer> cache = CacheBuilder.newBuilder()
.maximumSize(100)
.build();
cache.put("apple", 10);
System.out.println(cache.getIfPresent("apple")); // 10
3. Functional Programming Utilities
Guava includes utilities like Optional
, which represents a value that may or may not be present.
import com.google.common.base.Optional;
Optional<String> name = Optional.of("Guava");
System.out.println(name.isPresent()); // true
System.out.println(name.get()); // Guava
4. String Utilities
Guava provides helper methods for string manipulation.
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
String joined = Joiner.on(", ").join("apple", "banana", "guava");
System.out.println(joined); // apple, banana, guava
Iterable<String> parts = Splitter.on(", ").split("apple, banana, guava");
parts.forEach(System.out::println);
5. Hashing
Guava has powerful hashing utilities.
import com.google.common.hash.Hashing;
import java.nio.charset.StandardCharsets;
int hash = Hashing.murmur3_32().hashString("Guava", StandardCharsets.UTF_8).asInt();
System.out.println(hash);
6. Why Use Guava?
- Cleaner and safer code.
- Reduces boilerplate.
- Adds useful collection types and utilities not in Java standard library.
- Highly optimized and maintained by Google.