告别重复造轮子!Guava 工具包,让你早下班 1 小时
简介
Google Guava 是谷歌开发的基于 Java 的开源库,为 Java 项目提供了必要的实用工具。它涵盖了集合、缓存、基本类型支持、并发编程、常用注解、字符串处理、I/O 等功能。通过使用 Guava,开发者可以编写更简洁、高效且不易出错的代码。
安装
如果使用 Maven,在 pom.xml 中添加以下依赖:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.0.1-jre</version> <!-- 或最新版本 -->
</dependency>
对于 Gradle:
implementation 'com.google.guava:guava:31.0.1-jre' // 或最新版本
集合
不可变集合
不可变集合在创建后无法修改,这对线程安全和确保集合在生命周期内保持不变非常有用。
示例
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
public class ImmutableCollectionsExample {
public static void main(String[] args) {
ImmutableList<String> list = ImmutableList.of("a", "b", "c");
ImmutableSet<String> set = ImmutableSet.of("a", "b", "c");
ImmutableMap<String, Integer> map = ImmutableMap.of("a", 1, "b", 2, "c", 3);
System.out.println("Immutable List: " + list);
System.out.println("Immutable Set: " + set);
System.out.println("Immutable Map: " + map);
}
}
多重映射(Multimap)
Multimap 是一种将键映射到值的集合,其中每个键可以关联多个值。
示例
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
public class MultimapExample {
public static void main(String[] args) {
Multimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("fruit", "apple");
multimap.put("fruit", "banana");
multimap.put("vegetable", "carrot");
System.out.println("Multimap: " + multimap.get("fruit"));
//输出:Multimap: [apple, banana]
}
}
双向映射(BiMap)
BiMap 是一种保证键和值唯一性的映射,支持通过值查找键。
示例
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
public class BiMapExample {
public static void main(String[] args) {
BiMap<String, Integer> biMap = HashBiMap.create();
biMap.put("one", 1);
biMap.put("two", 2);
System.out.println("BiMap: " + biMap.get("one"));
//输出:BiMap: 1
System.out.println("Inverse BiMap: " + biMap.inverse().get(1));
//输出:Inverse BiMap: one
}
}
表格(Table)
Table 是一种表示两个键到单个值的映射的集合,类似于二维Map。
示例
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
public class TableExample {
public static void main(String[] args) {
Table<String, String, Integer> table = HashBasedTable.create();
table.put("row1", "column1", 1);
table.put("row1", "column2", 2);
table.put("row2", "column1", 3);
System.out.println("Table: " + table.get("row1", "column1"));
//输出:Table: 1
}
}
缓存
Guava 提供了强大且灵活的缓存 API,可用于创建和管理缓存。
示例
这段代码使用 Google Guava 库创建了一个本地缓存 LoadingCache
,功能如下:
- 创建一个最多存储 100 个条目的缓存;
- 缓存项在写入后 10 分钟过期;
- 当缓存中没有对应 key 的值时,通过
getDataFromDatabase(key)
方法加载数据。
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class CacheExample {
public static void main(String[] args) throws ExecutionException {
LoadingCache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(new CacheLoader<>() {
public String load(String key) {
return getDataFromDatabase(key);
}
});
System.out.println("Cache Value: " + cache.get("key"));
//输出:Cache Value: value
}
private static String getDataFromDatabase(String key) {
return "value"; // 模拟数据库调用
}
}
字符串处理
Guava 提供了各种字符串操作工具,如连接、拆分和转换。
连接(Joiner)
示例
import com.google.common.base.Joiner;
public class JoinerExample {
public static void main(String[] args) {
Joiner joiner = Joiner.on(", ").skipNulls();
String result = joiner.join("Harry", null, "Ron", "Hermione");
System.out.println("Joined String: " + result);
//输出:Joined String: Harry, Ron, Hermione
}
}
拆分(Splitter)
示例
import com.google.common.base.Splitter;
public class SplitterExample {
public static void main(String[] args) {
Iterable<String> result = Splitter.on(',').trimResults().omitEmptyStrings().split("foo,bar,, qux");
result.forEach(System.out::println);
//输出:
//foo
//bar
//qux
}
}
基本类型工具
Guava 提供了处理基本类型(如 Ints、Longs、Doubles)的工具。
示例
import com.google.common.primitives.Ints;
public class PrimitivesExample {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
System.out.println("Contains 3: " + Ints.contains(array, 3));
//输出:Contains 3: true
System.out.println("Max: " + Ints.max(array));
//输出:Max: 5
System.out.println("Min: " + Ints.min(array));
//输出:Min: 1
}
}
并发编程
Guava 提供了简化并发任务的工具,如 ListeningExecutorService,它扩展了 ExecutorService 以支持 ListenableFuture。
示例
这段代码使用了ListenableFuture
来执行异步任务并添加完成监听器。功能解释如下:
- 创建一个固定大小为10的线程池,并用
MoreExecutors.listeningDecorator
包装成ListeningExecutorService
。 - 提交一个返回字符串"Task Result"的任务。
- 为该任务添加监听器,任务完成后立即打印"Task completed!"。
- 阻塞获取任务结果并打印。
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
public class ConcurrencyExample {
public static void main(String[] args) throws Exception {
ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
ListenableFuture<String> future = service.submit(new Callable<>() {
public String call() {
return "Task Result";
}
});
future.addListener(() -> System.out.println("Task completed!"), MoreExecutors.directExecutor());
System.out.println("Result: " + future.get());
//输出:
//Task completed!
//Result: Task Result
}
}
I/O 操作
Guava 通过 Files 类简化了常见的 I/O 任务,如读取和写入文件。
示例
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class IOExample {
public static void main(String[] args) throws IOException {
File file = new File("example.txt");
String content = "Hello, Guava!";
Files.asCharSink(file, StandardCharsets.UTF_8).write(content);
String readContent = Files.asCharSource(file, StandardCharsets.UTF_8).read();
System.out.println("File Content: " + readContent);
//输出:File Content: Hello, Guava!
}
}
更多示例和用例
前置条件检查(Preconditions)
Guava 提供了 Preconditions 类,用于简化代码中的条件检查,尤其适用于验证方法参数。
示例
import com.google.common.base.Preconditions;
public class PreconditionsExample {
public static void main(String[] args) {
int age = -5;
Preconditions.checkArgument(age > 0, "Age must be positive");
}
}
可选值(Optional)
Guava 的 Optional 类用于表示可选(可为空)的值,避免使用 null 引用。
示例
import com.google.common.base.Optional;
public class OptionalExample {
public static void main(String[] args) {
Optional<Integer> possible = Optional.of(5);
System.out.println("Is present: " + possible.isPresent());
//输出:Is present: true
System.out.println("Value: " + possible.get());
//输出:Value: 5
Optional<Integer> absent = Optional.absent();
System.out.println("Is present: " + absent.isPresent());
//输出:Is present: false
}
}
排序(Ordering)
Ordering 类是用于创建和使用比较器的强大工具。
示例
import com.google.common.collect.Ordering;
import java.util.Arrays;
import java.util.List;
public class OrderingExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Dave");
Ordering<String> byLength = Ordering.natural().onResultOf(String::length);
List<String> sortedNames = byLength.sortedCopy(names);
System.out.println("Sorted by length: " + sortedNames);
//输出:Sorted by length: [Dave, Bob, Charlie, Alice]
}
}
范围(Range)
Range 类用于表示连续的值范围。
示例
import com.google.common.collect.Range;
public class RangeExample {
public static void main(String[] args) {
Range<Integer> range = Range.closed(1, 10);
System.out.println("Range: " + range);
//输出:Range: [1‥10]
System.out.println("Contains 5: " + range.contains(5));
//输出:Contains 5: true
System.out.println("Contains 15: " + range.contains(15));
//输出:Contains 15: false
System.out.println("Intersects [5, 7]: " + range.intersects(Range.closed(5, 7)));
//输出:Intersects [5, 7]: true
}
}
事件总线(EventBus)
EventBus 是一个发布/订阅事件系统,简化了组件之间的通信。
示例
这段代码演示了使用EventBus
进行事件发布与订阅的基本流程:
- 创建
EventBus
实例并注册监听器EventListener
; - 发布一个包含消息
"Hello EventBus!"
的EventMessage
事件; EventListener
接收到事件后,打印出事件内容。
核心功能:通过事件总线实现组件间解耦通信。
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
public class EventBusExample {
public static void main(String[] args) {
EventBus eventBus = new EventBus();
eventBus.register(new EventListener());
eventBus.post(new EventMessage("Hello EventBus!"));
}
static class EventMessage {
private final String message;
public EventMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
static class EventListener {
@Subscribe
public void listen(EventMessage eventMessage) {
System.out.println("Received message: " + eventMessage.getMessage());
//输出:Received message: Hello EventBus!
}
}
}
秒表(Stopwatch)
Stopwatch 类提供了简单的计时操作 API。
示例
import com.google.common.base.Stopwatch;
import java.util.concurrent.TimeUnit;
public class StopwatchExample {
public static void main(String[] args) throws InterruptedException {
Stopwatch stopwatch = Stopwatch.createStarted();
TimeUnit.SECONDS.sleep(2);
stopwatch.stop();
System.out.println("Elapsed time: " + stopwatch.elapsed(TimeUnit.SECONDS) + " seconds");
//输出:Elapsed time: 2 seconds
}
}
More Objects
Guava 提供了 MoreObjects 类,用于对象操作的实用方法,如通过 toStringHelper 生成 toString 方法。
示例
import com.google.common.base.MoreObjects;
public class MoreObjectsExample {
private final String name;
private final int age;
public MoreObjectsExample(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("name", name)
.add("age", age)
.toString();
}
public static void main(String[] args) {
MoreObjectsExample example = new MoreObjectsExample("John", 25);
System.out.println(example);
//输出:MoreObjectsExample{name=John, age=25}
}
}
哈希(Hashing)
Guava 提供了强大的哈希库,包含各种哈希算法。
示例
import com.google.common.hash.Hashing;
import com.google.common.hash.HashFunction;
import com.google.common.hash.HashCode;
import java.nio.charset.StandardCharsets;
public class HashingExample {
public static void main(String[] args) {
HashFunction hashFunction = Hashing.sha256();
HashCode hashCode = hashFunction.hashString("hello world", StandardCharsets.UTF_8);
System.out.println("Hash code: " + hashCode);
//输出:Hash code: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
}
}
字符匹配器(CharMatcher)
CharMatcher 类提供了处理字符和字符串的工具。
示例
import com.google.common.base.CharMatcher;
public class CharMatcherExample {
public static void main(String[] args) {
String input = "123abcXYZ";
String digits = CharMatcher.digit().retainFrom(input);
String letters = CharMatcher.javaLetter().retainFrom(input);
System.out.println("Digits: " + digits);
//输出:Digits: 123
System.out.println("Letters: " + letters);
//输出:Letters: abcXYZ
}
}
文件操作(Files)
Guava 的 Files 类提供了文件操作工具,如创建临时目录和简化文件操作。
示例:创建临时目录
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
public class CreateTempDirExample {
public static void main(String[] args) throws IOException {
File tempDir = Files.createTempDir();
System.out.println("Temporary Directory: " + tempDir.getAbsolutePath());
//输出:Temporary Directory: /tmp/temp-dir-1234567890
}
}
异常处理(Throwables)
Guava 提供了 Throwables 类来简化异常处理。
示例
import com.google.common.base.Throwables;
public class ThrowablesExample {
public static void main(String[] args) {
try {
throw new RuntimeException("Example exception");
} catch (RuntimeException e) {
System.out.println("Stack trace: " + Throwables.getStackTraceAsString(e));
}
}
}
比较链(ComparisonChain)
ComparisonChain 类简化了 compareTo 方法的实现。
示例
该代码定义了一个可比较的类 ComparisonChainExample
,使用 Comparable
接口实现对象间的自然排序。它通过 ComparisonChain
按照 name
和 age
字段依次进行比较:
- 先比较
name
(字符串比较) - 若
name
相同,则比较age
(数值比较) - 最终返回比较结果
示例中比较对象 a(“John”, 25) 与 b(“John”, 30),因 age
不同且前者更小,输出为 -1
。
import com.google.common.collect.ComparisonChain;
public class ComparisonChainExample implements Comparable<ComparisonChainExample> {
private final String name;
private final int age;
public ComparisonChainExample(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(ComparisonChainExample other) {
return ComparisonChain.start()
.compare(this.name, other.name)
.compare(this.age, other.age)
.result();
}
public static void main(String[] args) {
ComparisonChainExample a = new ComparisonChainExample("John", 25);
ComparisonChainExample b = new ComparisonChainExample("John", 30);
System.out.println("Comparison result: " + a.compareTo(b));
//输出:Comparison result: -1
}
}
最后
Google Guava 是一个功能强大的库,通过提供集合、缓存、并发、I/O 等工具,提升了 Java 开发效率。如需了解更多高级功能和详细文档,可以访问 官方 Guava 文档 https://github.com/google/guava。 借助 Guava,你可以利用其丰富的工具集,编写更高效、易读和可维护的 Java 代码。