1. 集合工具類(com.google.common.collect
)
Guava 對 Java 集合框架進行了豐富擴展,解決了標準集合的諸多痛點。
(1)Lists
?/?Sets
?/?Maps
:用于簡化集合創建和操作:
// 創建不可變集合(線程安全,不可修改)
List<String> immutableList = Lists.newArrayList("a", "b", "c");
Set<Integer> immutableSet = Sets.newHashSet(1, 2, 3);
Map<String, Integer> immutableMap = Maps.newHashMap();// 集合操作(如合并、差集、交集)
Set<Integer> set1 = Sets.newHashSet(1, 2, 3);
Set<Integer> set2 = Sets.newHashSet(3, 4, 5);
Sets.SetView<Integer> union = Sets.union(set1, set2); // {1,2,3,4,5}
Sets.SetView<Integer> intersection = Sets.intersection(set1, set2); // {3}// 快速創建初始化大小的集合(避免擴容開銷)
List<String> capacityList = Lists.newArrayListWithCapacity(100);
(2)ImmutableXXX
(不可變集合)不可變集合一旦創建就不能修改,線程安全且性能更好:
// 不可變列表
ImmutableList<String> list = ImmutableList.of("a", "b", "c");// 不可變映射
ImmutableMap<String, Integer> map = ImmutableMap.of("one", 1,"two", 2
);// 構建復雜不可變集合
ImmutableSet<String> set = ImmutableSet.<String>builder().add("x").addAll(Sets.newHashSet("y", "z")).build();
(3)Multimap
(多值映射)解決一個鍵對應多個值的場景(無需手動創建?Map<K, List<V>>
):
Multimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("fruit", "apple");
multimap.put("fruit", "banana");
multimap.put("color", "red");// 獲取鍵對應的所有值
Collection<String> fruits = multimap.get("fruit"); // [apple, banana]// 轉換為普通Map
Map<String, Collection<String>> map = multimap.asMap();
2. 字符串工具類(com.google.common.base
)
(1)Strings
提供字符串常見操作:
// 空字符串處理
Strings.isNullOrEmpty(""); // true
Strings.nullToEmpty(null); // 轉為空字符串""
Strings.emptyToNull(""); // 轉為null// 填充字符串(左對齊/右對齊)
Strings.padStart("123", 5, '0'); // "00123"(總長度5,不足補0)
Strings.padEnd("123", 5, '0'); // "12300"// 重復字符串
Strings.repeat("ab", 3); // "ababab"
(2)Joiner
?/?Splitter
更靈活的字符串拼接與拆分:
// 拼接(自動處理null和空值)
Joiner joiner = Joiner.on(",").skipNulls(); // 用逗號拼接,跳過null
String result = joiner.join("a", null, "b"); // "a,b"// 拼接Map
Joiner mapJoiner = Joiner.on(";").withKeyValueSeparator("=");
mapJoiner.join(ImmutableMap.of("name", "Alice", "age", "30")); // "name=Alice;age=30"// 拆分(支持更復雜的規則)
Splitter splitter = Splitter.on(",").trimResults().omitEmptyStrings();
List<String> parts = splitter.splitToList(" a , , b "); // ["a", "b"]// 按固定長度拆分
Splitter.fixedLength(2).split("abcdef"); // ["ab", "cd", "ef"]
3. 緩存工具類(com.google.common.cache
)
Cache
?是輕量級本地緩存實現,比?HashMap
?多了過期策略、加載機制等:
// 創建緩存(設置最大容量和過期時間)
LoadingCache<String, String> cache = CacheBuilder.newBuilder().maximumSize(1000) // 最大緩存項數.expireAfterWrite(10, TimeUnit.MINUTES) // 寫入后10分鐘過期.build(new CacheLoader<String, String>() {// 緩存未命中時的加載邏輯@Overridepublic String load(String key) {return fetchFromDatabase(key); // 從數據庫加載數據}});// 使用緩存
try {String value = cache.get("key1"); // 存在則返回,否則調用load()加載
} catch (ExecutionException e) {// 處理異常
}// 手動放入緩存
cache.put("key2", "value2");// 移除緩存
cache.invalidate("key1");
4. 并發工具類(com.google.common.util.concurrent
)
(1)ListenableFuture
增強版?Future
,支持添加回調函數,避免阻塞等待:
// 創建線程池
ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(5)
);// 提交任務,返回ListenableFuture
ListenableFuture<String> future = executor.submit(() -> {Thread.sleep(1000);return "任務結果";
});// 添加回調(任務完成時自動執行)
Futures.addCallback(future, new FutureCallback<String>() {@Overridepublic void onSuccess(String result) {System.out.println("成功:" + result);}@Overridepublic void onFailure(Throwable t) {System.err.println("失敗:" + t.getMessage());}
}, executor);
5. 基本類型工具類(com.google.common.primitives
)
針對?int
、long
、boolean
?等基本類型提供工具方法:
// Ints:int類型工具
Ints.contains(new int[]{1, 2, 3}, 2); // true
Ints.max(1, 3, 5); // 5
List<Integer> intList = Ints.asList(1, 2, 3); // 轉為List<Integer>// 類似的還有Longs、Doubles、Booleans等
6. 時間工具類(com.google.common.base
)
(1)Stopwatch
精確測量代碼執行時間
// 1. 創建 Stopwatch 實例(未啟動)
Stopwatch stopwatch = Stopwatch.createUnstarted();// 2. 開始計時
stopwatch.start();// ----------------------
// 目標代碼:模擬耗時操作(如接口調用、數據處理)
Thread.sleep(1500); // 模擬1.5秒耗時
// ----------------------// 3. 停止計時
stopwatch.stop();// 4. 獲取耗時(支持多種時間單位)
long elapsedMs = stopwatch.elapsed(TimeUnit.MILLISECONDS); // 毫秒:1500左右
long elapsedNs = stopwatch.elapsed(TimeUnit.NANOSECONDS); // 納秒:1500000000左右
long elapsedS = stopwatch.elapsed(TimeUnit.SECONDS); // 秒:1(向下取整)
7. 謂詞與函數(com.google.common.base
)
(1)Predicate
(謂詞,用于條件判斷)
Predicate<String> isLongThan3 = s -> s.length() > 3;
List<String> list = Lists.newArrayList("a", "bb", "ccc", "dddd");
// 過濾符合條件的元素
List<String> filtered = Lists.newArrayList(Iterables.filter(list, isLongThan3));
(2)Function
(函數,用于類型轉換)
Function<String, Integer> strToInt = Integer::parseInt;
List<String> strList = Lists.newArrayList("1", "2", "3");
// 轉換為Integer列表
List<Integer> intList = Lists.transform(strList, strToInt);
8. 前置條件(com.google.common.base.Preconditions
)
簡化參數校驗代碼:Spring 框架的?Assert
?類(org.springframework.util.Assert
)與 Guava?Preconditions
?功能類似,常用于 Spring 項目中的參數校驗:
public void process(String name, int age) {// 校驗參數,失敗則拋出異常Preconditions.checkNotNull(name, "名稱不能為空");Preconditions.checkArgument(age > 0, "年齡必須為正數:%s", age);Preconditions.checkState(age < 150, "年齡不能超過150");
}
引入依賴
使用 Guava 需在項目中引入依賴(以 Maven 為例):
<dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>32.1.3-jre</version> <!-- 版本可按需更新 -->
</dependency>