0
# Google Guava
1
2
Google Guava is a comprehensive Java library that provides essential utilities and data structures for modern Java development. It includes immutable collections, caching, concurrency utilities, I/O helpers, string manipulation, and much more.
3
4
## Package Information
5
6
**Name:** `com.google.guava:guava`
7
**Type:** Library
8
**Language:** Java
9
**Version:** 33.4.8
10
11
### Installation
12
13
Add this Maven dependency:
14
15
```xml { .api }
16
<dependency>
17
<groupId>com.google.guava</groupId>
18
<artifactId>guava</artifactId>
19
<version>33.4.8-jre</version>
20
</dependency>
21
```
22
23
## Core Imports
24
25
```java { .api }
26
// Basic utilities
27
import com.google.common.base.*;
28
import com.google.common.collect.*;
29
30
// Specialized functionality
31
import com.google.common.cache.*;
32
import com.google.common.util.concurrent.*;
33
import com.google.common.io.*;
34
import com.google.common.hash.*;
35
import com.google.common.math.*;
36
```
37
38
## Basic Usage
39
40
### String Utilities
41
42
```java { .api }
43
import com.google.common.base.Strings;
44
import com.google.common.base.Joiner;
45
import com.google.common.base.Splitter;
46
47
// Null-safe string operations
48
String safe = Strings.nullToEmpty(null); // ""
49
boolean empty = Strings.isNullOrEmpty(""); // true
50
51
// Joining strings
52
String result = Joiner.on(", ").skipNulls().join("a", null, "b"); // "a, b"
53
54
// Splitting strings
55
List<String> parts = Splitter.on(',').trimResults().splitToList("a, b , c");
56
```
57
58
### Collections
59
60
```java { .api }
61
import com.google.common.collect.Lists;
62
import com.google.common.collect.ImmutableList;
63
64
// Creating lists
65
List<String> list = Lists.newArrayList("a", "b", "c");
66
67
// Immutable collections
68
ImmutableList<String> immutable = ImmutableList.of("a", "b", "c");
69
ImmutableList<String> copy = ImmutableList.copyOf(existingList);
70
```
71
72
### Validation
73
74
```java { .api }
75
import com.google.common.base.Preconditions;
76
77
// Method precondition checking
78
public void setAge(int age) {
79
Preconditions.checkArgument(age >= 0, "Age must be non-negative: %s", age);
80
Preconditions.checkNotNull(name, "Name cannot be null");
81
this.age = age;
82
}
83
```
84
85
## Architecture
86
87
Guava is organized into several key capability areas:
88
89
### Core Utilities
90
- **Basic Utilities**: String manipulation, preconditions, null handling, and object utilities
91
- **Collections**: Enhanced collection types, utilities, and transformations
92
- **Immutable Collections**: Thread-safe, high-performance immutable data structures
93
94
### Specialized Features
95
- **Caching**: Flexible in-memory caching with automatic loading and expiration
96
- **Concurrency**: Enhanced futures, executors, and synchronization primitives
97
- **I/O Utilities**: Stream processing, file operations, and resource management
98
99
### Advanced Capabilities
100
- **Hash & Math**: Hash functions, mathematical operations with overflow checking
101
- **Graph API**: Graph data structures and algorithms
102
- **Other Utilities**: Event bus, escaping, networking, reflection, and primitives
103
104
## Capabilities
105
106
### Basic Utilities
107
108
Essential utilities for common programming tasks including annotations, string manipulation, preconditions, and object helpers.
109
110
```java { .api }
111
import com.google.common.base.Preconditions;
112
import com.google.common.base.Strings;
113
import com.google.common.base.Objects;
114
115
// Precondition checking
116
Preconditions.checkArgument(count >= 0);
117
Preconditions.checkNotNull(value);
118
119
// String utilities
120
String padded = Strings.padStart("42", 5, '0'); // "00042"
121
String common = Strings.commonPrefix("foobar", "foobaz"); // "fooba"
122
123
// Object utilities
124
boolean equal = Objects.equal(a, b); // null-safe
125
int hash = Objects.hashCode(field1, field2, field3);
126
```
127
128
**→** [Basic Utilities](./basic-utilities.md) - Complete utilities for annotations, strings, validation, objects, and functional programming
129
130
### Collections
131
132
Enhanced collection types and utilities including multimaps, multisets, and powerful collection transformations.
133
134
```java { .api }
135
import com.google.common.collect.*;
136
137
// Multimap - key to multiple values
138
ListMultimap<String, String> multimap = ArrayListMultimap.create();
139
multimap.put("fruits", "apple");
140
multimap.put("fruits", "banana");
141
142
// Multiset - collection with duplicates and counts
143
Multiset<String> counts = HashMultiset.create();
144
counts.add("apple", 3);
145
int appleCount = counts.count("apple"); // 3
146
147
// BiMap - bidirectional map
148
BiMap<String, Integer> bimap = HashBiMap.create();
149
bimap.put("one", 1);
150
Integer value = bimap.get("one"); // 1
151
String key = bimap.inverse().get(1); // "one"
152
```
153
154
**→** [Collections](./collections.md) - Comprehensive collection utilities, multimaps, multisets, and advanced data structures
155
156
### Immutable Collections
157
158
Thread-safe, high-performance immutable data structures that can be safely shared and cached.
159
160
```java { .api }
161
import com.google.common.collect.*;
162
163
// Immutable list
164
ImmutableList<String> list = ImmutableList.of("a", "b", "c");
165
ImmutableList<String> built = ImmutableList.<String>builder()
166
.add("x")
167
.addAll(otherList)
168
.build();
169
170
// Immutable map
171
ImmutableMap<String, Integer> map = ImmutableMap.of(
172
"one", 1,
173
"two", 2,
174
"three", 3
175
);
176
177
// Immutable set with natural ordering
178
ImmutableSortedSet<String> sorted = ImmutableSortedSet.of("c", "a", "b");
179
```
180
181
**→** [Immutable Collections](./immutable-collections.md) - Complete guide to immutable lists, sets, maps, and sorted collections
182
183
### Caching
184
185
Flexible in-memory caching with automatic loading, expiration, and comprehensive statistics.
186
187
```java { .api }
188
import com.google.common.cache.*;
189
import java.util.concurrent.TimeUnit;
190
191
// Cache with automatic loading
192
LoadingCache<String, String> cache = CacheBuilder.newBuilder()
193
.maximumSize(1000)
194
.expireAfterWrite(10, TimeUnit.MINUTES)
195
.build(new CacheLoader<String, String>() {
196
public String load(String key) {
197
return loadFromDatabase(key);
198
}
199
});
200
201
String value = cache.get("key"); // Loads automatically if absent
202
cache.invalidate("key"); // Remove specific entry
203
```
204
205
**→** [Caching](./caching.md) - Complete caching solution with loading, expiration, and eviction strategies
206
207
### Concurrency
208
209
Enhanced concurrency utilities including listenable futures, rate limiting, and improved executors.
210
211
```java { .api }
212
import com.google.common.util.concurrent.*;
213
import java.util.concurrent.Executors;
214
215
// Listenable futures
216
ListeningExecutorService executor = MoreExecutors.listeningDecorator(
217
Executors.newFixedThreadPool(10));
218
219
ListenableFuture<String> future = executor.submit(callable);
220
Futures.addCallback(future, new FutureCallback<String>() {
221
public void onSuccess(String result) { /* handle success */ }
222
public void onFailure(Throwable t) { /* handle failure */ }
223
}, MoreExecutors.directExecutor());
224
225
// Rate limiting
226
RateLimiter rateLimiter = RateLimiter.create(5.0); // 5 permits per second
227
rateLimiter.acquire(); // Blocks until permit available
228
```
229
230
**→** [Concurrency](./concurrency.md) - Advanced concurrency with ListenableFuture, rate limiting, and services
231
232
### I/O Utilities
233
234
Comprehensive I/O utilities for streams, files, and resource management with proper exception handling.
235
236
```java { .api }
237
import com.google.common.io.*;
238
import java.io.File;
239
import java.nio.charset.StandardCharsets;
240
241
// File operations
242
List<String> lines = Files.readLines(file, StandardCharsets.UTF_8);
243
Files.write("Hello World".getBytes(), file);
244
245
// Resource operations
246
URL resource = Resources.getResource("config.properties");
247
String content = Resources.toString(resource, StandardCharsets.UTF_8);
248
249
// Stream copying
250
ByteStreams.copy(inputStream, outputStream);
251
CharStreams.copy(reader, writer);
252
```
253
254
**→** [I/O Utilities](./io-utilities.md) - File operations, resource handling, and stream processing utilities
255
256
### Graph API
257
258
Powerful graph data structures and algorithms for modeling complex relationships.
259
260
```java { .api }
261
import com.google.common.graph.*;
262
263
// Mutable graph
264
MutableGraph<String> graph = GraphBuilder.undirected().build();
265
graph.addNode("A");
266
graph.addNode("B");
267
graph.putEdge("A", "B");
268
269
// Graph queries
270
Set<String> neighbors = graph.adjacentNodes("A");
271
boolean connected = graph.hasEdgeConnecting("A", "B");
272
int degree = graph.degree("A");
273
```
274
275
**→** [Graph API](./graph-api.md) - Graph data structures, algorithms, and network modeling
276
277
### Hash and Math
278
279
Hash functions and mathematical operations with overflow checking and precision handling.
280
281
```java { .api }
282
import com.google.common.hash.*;
283
import com.google.common.math.IntMath;
284
import java.math.RoundingMode;
285
286
// Hashing
287
HashFunction hasher = Hashing.sha256();
288
HashCode hash = hasher.hashString("input", StandardCharsets.UTF_8);
289
290
// Safe math operations
291
int sum = IntMath.checkedAdd(a, b); // Throws on overflow
292
int sqrt = IntMath.sqrt(x, RoundingMode.HALF_UP);
293
int gcd = IntMath.gcd(a, b);
294
```
295
296
**→** [Hash and Math](./hash-math.md) - Hash functions, mathematical utilities, and statistical operations
297
298
### Other Utilities
299
300
Additional utilities including event bus, escaping, networking, reflection, and primitive operations.
301
302
```java { .api }
303
import com.google.common.eventbus.EventBus;
304
import com.google.common.net.HostAndPort;
305
import com.google.common.primitives.Ints;
306
307
// Event bus
308
EventBus eventBus = new EventBus();
309
eventBus.register(listenerObject);
310
eventBus.post(new SomeEvent());
311
312
// Network utilities
313
HostAndPort hostPort = HostAndPort.fromString("example.com:8080");
314
String host = hostPort.getHost(); // "example.com"
315
int port = hostPort.getPort(); // 8080
316
317
// Primitive utilities
318
List<Integer> intList = Ints.asList(1, 2, 3, 4, 5);
319
int[] array = Ints.toArray(intList);
320
```
321
322
**→** [Other Utilities](./other-utilities.md) - Event bus, networking, escaping, reflection, and primitive utilities
323
324
## Key Design Principles
325
326
- **Immutability**: Extensive use of immutable data structures for thread safety and performance
327
- **Null Safety**: Careful handling of null values throughout the API
328
- **Functional Programming**: Function, Predicate, and Supplier interfaces for functional composition
329
- **Builder Pattern**: Fluent builders for creating complex objects
330
- **Static Utilities**: Comprehensive utility methods for common programming tasks
331
- **Fail-Fast**: Early detection of programming errors through precondition checking