Guava (Google Guava) is a Java library developed by Google that provides many practical tools and basic libraries to simplify common tasks of Java programming. Here are some of Guava’s main features and usage guidelines:
1. Collections:
-
Immutable Collections: Guava provides a series of immutable collections that cannot be modified after creation, providing a safer and more efficient way to handle them. data.
Iterable<String> splitResult = Splitter.on(',').trimResults().omitEmptyStrings().split("apple, banana, orange"); String joinedString = Joiner.on("; ").join(splitResult);
-
New collection types: Guava introduces many new collection types, such as
Multiset
,Multimap
, a>BiMap
etc. to support more complex data structures.
2. String processing:
-
String splitting and concatenation: Guava provides tool classes for string splitting and concatenation, such as
Splitter
and < a i=3>.Joiner
Cache<String, Integer> cache = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterWrite(10, TimeUnit.MINUTES) .build();
3. Caching:
-
Local Cache: Guava's
Cache
interface provides the implementation of local cache and supports setting expiration time, cache recycling, etc.Cache<String, Integer> cache = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterWrite(10, TimeUnit.MINUTES) .build();
4. Event bus:
-
EventBus: Guava provides a simple event bus for publishing and subscribing events between components.
// 定义事件 public static class Event { // ... } // 注册和发布事件 EventBus eventBus = new EventBus(); eventBus.register(new Object() { @Subscribe public void handleEvent(Event event) { // 处理事件 } }); eventBus.post(new Event());
5. Functional programming:
-
Functional tool classes: Guava contains many functional programming tool classes, such as
Function
,Predicate
,Optional
etc.// 使用Function进行映射 List<String> transformedList = Lists.transform(originalList, input -> input.toUpperCase()); // 使用Predicate进行过滤 List<String> filteredList = Lists.newArrayList(Collections2.filter(originalList, input -> input.length() > 5));
6. Predictive caching:
-
LoadingCache:
LoadingCache
is an interface in Guava that provides a mechanism for loading values in the cache. You can define how to load missing values from the cache by implementing theCacheLoader
interface.LoadingCache<String, Integer> cache = CacheBuilder.newBuilder() .maximumSize(100) .build(new CacheLoader<String, Integer>() { @Override public Integer load(String key) throws Exception { // 在缓存中没有找到值时的加载逻辑 return computeValue(key); } });
7. Expression assertion:
-
Preconditions: Guava's
Preconditions
class provides a set of static methods for expression assertions for preconditioning inside methods examine.public void process(String data) { Preconditions.checkNotNull(data, "Data cannot be null"); Preconditions.checkArgument(!data.isEmpty(), "Data cannot be empty"); // 继续处理数据 }
8. Concurrency tools:
-
ListenableFuture: Guava provides support for
ListenableFuture
to easily listen for completion events of asynchronous operations.ListenableFuture<String> future = executorService.submit(() -> computeResult()); Futures.addCallback(future, new FutureCallback<String>() { @Override public void onSuccess(@Nullable String result) { // 处理成功的情况 } @Override public void onFailure(Throwable t) { // 处理失败的情况 } }, executorService);
9. Byte stream processing:
-
ByteStreams: Guava provides the
ByteStreams
class for processing byte streams. For example, you can use it to convertInputStream
tobyte[]
.byte[] byteArray = ByteStreams.toByteArray(inputStream);
10. Advanced string processing:
-
CharMatcher:
CharMatcher
The class provides rich character matching and processing functions, such as deleting, retaining, replacing characters, etc.String stringWithoutDigits = CharMatcher.digit().removeFrom("abc123def");
11. Time tools:
-
Stopwatch:
Stopwatch
The class is used to measure time intervals to facilitate monitoring of code execution time.Stopwatch stopwatch = Stopwatch.createStarted(); // 执行一些操作 long elapsedMillis = stopwatch.elapsed(TimeUnit.MILLISECONDS);
12. Event bus enhancement:
-
@Subscribe annotation: Guava's
@Subscribe
annotation simplifies the definition of event subscription methods and makes the code clearer.@Subscribe public void handleEvent(Event event) { // 处理事件 }
13. File operations:
-
MoreFiles:
MoreFiles
The class provides some additional file operations, such as recursively listing all files in a directory.List<Path> allFiles = Lists.newArrayList(MoreFiles.fileTraverser().depthFirstPreOrder(Paths.get("/path/to/directory")));
14. Mark interface:
-
@Beta annotation: Guava's
@Beta
annotation marks some APIs under experimentation to remind developers that these APIs may be included in future versions changes occur.@Beta public interface SomeExperimentalInterface { // Experimental code }
15. Collection operations:
-
Sets:
Sets
The class provides a series of useful set operations, such as intersection, union, difference, etc.Set<Integer> set1 = ImmutableSet.of(1, 2, 3); Set<Integer> set2 = ImmutableSet.of(2, 3, 4); Set<Integer> union = Sets.union(set1, set2); // {1, 2, 3, 4} Set<Integer> intersection = Sets.intersection(set1, set2); // {2, 3}
16. Comparator:
-
Ordering:
Ordering
The class provides a set of powerful comparators to simplify comparison operations and support chain calls.List<String> strings = ImmutableList.of("apple", "banana", "orange"); strings = Ordering.natural().reverse().sortedCopy(strings);
17. Array tools:
-
ObjectArrays:
ObjectArrays
The class provides some basic operations on object arrays, such as merging, searching, determining equality, etc.String[] array1 = {"apple", "banana"}; String[] array2 = {"orange", "grape"}; String[] mergedArray = ObjectArrays.concat(array1, array2, String.class);
18. Exception tools:
-
Throwables:
Throwables
The class provides some useful exception handling tools, such as checking the type of exception, locating the original exception according to the cause chain, etc.try { // some code that may throw an exception } catch (Exception e) { if (Throwables.getRootCause(e) instanceof MyCustomException) { // handle specific exception type } }
19. Basic type operations:
-
Booleans, Ints, Longs: Guava provides a series of basic type operation classes to facilitate comparison and operation of basic types.
int maxInt = Ints.max(1, 3, 5); // 5 boolean containsTrue = Booleans.contains(new boolean[]{true, false, true}, true); // true
20. Interval operation:
-
Ranges:
Ranges
The class provides a set of facilities for representing and manipulating ranges. This is useful for working with numbers, date ranges, etc.Range<Integer> range = Range.closed(1, 10); // [1, 10] boolean contains = range.contains(5); // true
21. Non-empty judgment:
-
Preconditions.checkNotNull: The method in Guava's
Preconditions
class can be conveniently used to check whether the parameter is null.checkNotNull
public void process(String data) { Preconditions.checkNotNull(data, "Data cannot be null"); // 继续处理数据 }
22. Character encoding:
-
The Charsets:
Charsets
class defines constants for some common character sets, which is very useful when dealing with string encodings.byte[] utf8Bytes = "Hello, Guava!".getBytes(Charsets.UTF_8);
23. Mathematical operations:
-
BigIntegerMath, DoubleMath: Guava provides some additional mathematical operation tool classes for processing large integers, floating point numbers, etc.
BigInteger factorial = BigIntegerMath.factorial(5); // 120 double roundedPi = DoubleMath.roundToLong(Math.PI, RoundingMode.HALF_UP); // 3
24. Type tools:
-
TypeToken:
TypeToken
The class is used to parse and process generic types, providing the ability to obtain generic type information at runtime.TypeToken<List<String>> stringListToken = new TypeToken<List<String>>() {};
These are only a small part of the functions provided by the Guava library. Detailed usage documentation and examples can be found in the Guava official documentation: Guava Wiki. According to the project needs, choosing the appropriate Guava module and reading the documentation carefully will effectively improve the efficiency of Java programming.