最近在看一個同學代碼的時候,發現代碼中大量使用了 Google 開源的 Guava 核心庫中的內容,讓代碼簡單清晰了不少,故學習分享出 Guava 中我認為最實用的功能。
Guava項目是 Google 公司開源的 Java 核心庫,它主要是包含一些在 Java 開發中經常使用到的功能,如 數據校驗 、 不可變集合 、計數集合,集合增強操作、I/O、緩存、字符串操作等。并且Guava 廣泛用于 Google 內部的 Java 項目中,也被其他公司廣泛使用,甚至在新版 JDK 中直接引入了 Guava 中的優秀類庫,所以質量毋庸置疑。
使用方式直接 mavan 依賴引入。
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.0-jre</version>
</dependency>
數據校驗
數據校驗說來十分簡單,一是 非空判斷 ,二是 預期值判斷 。非空判斷我想每一個 Java 開發者都很熟悉,一開始都經常和 NullPointException 打交道。處理的方式我們自然是一個 if( xx == null)就能輕松解決。預期值判斷也是類似,檢查數據值是不是自己想要的結果即可。
即使這么簡單的操作,我們是不是還經常出錯呢?而且寫起來的代碼總是一行判斷一行異常突出,怎么看都覺得那么優雅。還好,現在就來嘗試第一次使用 Guava 吧。
非空判斷
String param = "未讀代碼";
String name = Preconditions.checkNotNull(param);
System.out.println(name); // 未讀代碼
String param2 = null;
String name2 = Preconditions.checkNotNull(param2); // NullPointerException
System.out.println(name2);
引入了 Guava 后可以直接使用 Preconditions.checkNotNull 進行非空判斷,好處為覺得有兩個,一是語義清晰代碼優雅;二是你也可以自定義報錯信息,這樣如果參數為空,報錯的信息清晰,可以直接定位到具體參數。
String param2 = null;
String name2 = Preconditions.checkNotNull(param2,"param2 is null");
// java.lang.NullPointerException: param2 is null
預期值判斷
和非空判斷類似,可以比較當前值和預期值,如果不相等可以自定義報錯信息拋出。
String param = "www.wdbyte.com2";
String wdbyte = "www.wdbyte.com";
Preconditions.checkArgument(wdbyte.equals(param), "[%s] 404 NOT FOUND", param);
// java.lang.IllegalArgumentException: [www.wdbyte.com2] 404 NOT FOUND
是否越界
Preconditions 類還可以用來檢查數組和集合的元素獲取是否越界。
// Guava 中快速創建ArrayList
List<String> list = Lists.newArrayList("a", "b", "c", "d");
// 開始校驗
int index = Preconditions.checkElementIndex(5, list.size());
// java.lang.IndexOutOfBoundsException: index (5) must be less than size (4)
代碼中快速創建 List 的方式也是 Guava 提供的,后面會詳細介紹 Guava 中集合創建的超多姿勢。
不可變的集合
創建不可變集合是我個人最喜歡 Guava 的一個原因,因為創建一個 不能刪除、不能修改、不能增加元素 的集合實在是太實用了。這樣的集合你完全不用擔心發生什么問題,總的來說有下面幾個優點:
- 線程安全,因為不能修改任何元素,可以隨意多線程使用且沒有并發問題。
- 可以無憂的提供給第三方使用,反正修改不了。
- 減少內存占用,因為不能改變,所以內部實現可以最大程度節約內存占用。
- 可以用作常量集合。
創建方式
說了那么多,那么到底怎么使用呢?趕緊擼起代碼來。
// 創建方式1:of
ImmutableSet<String> immutableSet = ImmutableSet.of("a", "b", "c");
immutableSet.forEach(System.out::println);
// a
// b
// c
// 創建方式2:builder
ImmutableSet<String> immutableSet2 = ImmutableSet.<String>builder()
.add("hello")
.add(new String("未讀代碼"))
.build();
immutableSet2.forEach(System.out::println);
// hello
// 未讀代碼
// 創建方式3:從其他集合中拷貝創建
ArrayList<String> arrayList = new ArrayList();
arrayList.add("www.wdbyte.com");
arrayList.add("https");
ImmutableSet<String> immutableSet3 = ImmutableSet.copyOf(arrayList);
immutableSet3.forEach(System.out::println);
// www.wdbyte.com
// https
都可以正常打印遍歷結果,但是如果進行增刪改,會直接報 UnsupportedOperationException.
其實 JDK 中也提供了一個不可變集合,可以像下面這樣創建。
ArrayList<String> arrayList = new ArrayList();
arrayList.add("www.wdbyte.com");
arrayList.add("https");
// JDK Collections 創建不可變 List
List<String> list = Collections.unmodifiableList(arrayList);
list.forEach(System.out::println);// www.wdbyte.com https
list.add("未讀代碼"); // java.lang.UnsupportedOperationException
注意事項
- 使用 Guava 創建的不可變集合是拒絕 null 值的,因為在 Google 內部調查中,95% 的情況下都不需要放入 null 值。
- 使用 JDK 提供的不可變集合創建成功后,原集合添加元素會體現在不可變集合中,而 Guava 的不可變集合不會有這個問題。
List<String> arrayList = new ArrayList<>();
arrayList.add("a");
arrayList.add("b");
List<String> jdkList = Collections.unmodifiableList(arrayList);
ImmutableList<String> immutableList = ImmutableList.copyOf(arrayList);
arrayList.add("ccc");
jdkList.forEach(System.out::println);// result: a b ccc
System.out.println("-------");
immutableList.forEach(System.out::println);// result: a b
- 如果不可變集合的元素是引用對象,那么引用對象的屬性是可以更改的。
其他不可變集合
不可變集合除了上面演示的 set 之外,還有很多不可變集合,下面是 Guava 中不可變集合和其他集合的對應關系。
集合操作工廠
其實這里只會介紹一個創建方法,但是為什么還是單獨拿出來介紹了呢?看下去你就會 大呼好用 。雖然 JDK 中已經提供了大量的集合相關的操作方法,用起來也是非常的方便,但是 Guava 還是增加了一些十分好用的方法,保證讓你用上一次就愛不釋手,
創建集合。
// 創建一個 ArrayList 集合
List<String> list1 = Lists.newArrayList();
// 創建一個 ArrayList 集合,同時塞入3個數據
List<String> list2 = Lists.newArrayList("a", "b", "c");
// 創建一個 ArrayList 集合,容量初始化為10
List<String> list3 = Lists.newArrayListWithCapacity(10);
LinkedList<String> linkedList1 = Lists.newLinkedList();
CopyOnWriteArrayList<String> cowArrayList = Lists.newCopyOnWriteArrayList();
HashMap<Object, Object> hashMap = Maps.newHashMap();
ConcurrentMap<Object, Object> concurrentMap = Maps.newConcurrentMap();
TreeMap<Comparable, Object> treeMap = Maps.newTreeMap();
HashSet<Object> hashSet = Sets.newHashSet();
HashSet<String> newHashSet = Sets.newHashSet("a", "a", "b", "c");
Guava 為每一個集合都添加了工廠方法創建方式,上面已經展示了部分集合的工廠方法創建方式。是不是十分的好用呢。而且可以在創建時直接扔進去幾個元素,這個簡直太贊了,再也不用一個個add 了。
集合交集并集差集
過于簡單,直接看代碼和輸出結果吧。
Set<String> newHashSet1 = Sets.newHashSet("a", "a", "b", "c");
Set<String> newHashSet2 = Sets.newHashSet("b", "b", "c", "d");
// 交集
SetView<String> intersectionSet = Sets.intersection(newHashSet1, newHashSet2);
System.out.println(intersectionSet); // [b, c]
// 并集
SetView<String> unionSet = Sets.union(newHashSet1, newHashSet2);
System.out.println(unionSet); // [a, b, c, d]
// newHashSet1 中存在,newHashSet2 中不存在
SetView<String> setView = Sets.difference(newHashSet1, newHashSet2);
System.out.println(setView); // [a]
有數量的集合
這個真的太有用了,因為我們經常會需要設計可以計數的集合,或者 value 是 List 的 Map 集合,如果說你不太明白,看下面這段代碼,是否某天夜里你也這樣寫過。
- 統計相同元素出現的次數(下面的代碼我已經盡可能精簡寫法了)。JDK 原生寫法:
// Java 統計相同元素出現的次數。
List<String> words = Lists.newArrayList("a", "b", "c", "d", "a", "c");
Map<String, Integer> countMap = new HashMap<String, Integer>();
for (String word : words) {
Integer count = countMap.get(word);
count = (count == null) ? 1 : ++count;
countMap.put(word, count);
}
countMap.forEach((k, v) -> System.out.println(k + ":" + v));
/**
* result:
* a:2
* b:1
* c:2
* d:1
*/
盡管已經盡量優化代碼,代碼量還是不少的,那么在 Guava 中有什么不一樣呢?在 Guava. 中主要是使用 HashMultiset 類,看下面。
ArrayList<String> arrayList = Lists.newArrayList("a", "b", "c", "d", "a", "c");
HashMultiset<String> multiset = HashMultiset.create(arrayList);
multiset.elementSet().forEach(s -> System.out.println(s + ":" + multiset.count(s)));
/**
* result:
* a:2
* b:1
* c:2
* d:1
*/
是的,只要把元素添加進去就行了,不用在乎是否重復,最后都可以使用 count 方法統計重復元素數量。看著舒服,寫著優雅, HashMultiset 是 Guava 中實現的 Collection 類,可以輕松統計元素數量。
- 一對多,value 是 List 的 Map 集合。假設一個場景,需要把很多動物按照種類進行分類,我相信最后你會寫出類似的代碼。JDK 原生寫法:
HashMap<String, Set<String>> animalMap = new HashMap<>();
HashSet<String> dogSet = new HashSet<>();
dogSet.add("旺財");
dogSet.add("大黃");
animalMap.put("狗", dogSet);
HashSet<String> catSet = new HashSet<>();
catSet.add("加菲");
catSet.add("湯姆");
animalMap.put("貓", catSet);
System.out.println(animalMap.get("貓")); // [加菲, 湯姆]
最后一行查詢貓得到了貓類的 "加菲" 和 ”湯姆“。這個代碼簡直太煩瑣了,如果使用 Guava 呢?
// use guava
HashMultimap<String, String> multimap = HashMultimap.create();
multimap.put("狗", "大黃");
multimap.put("狗", "旺財");
multimap.put("貓", "加菲");
multimap.put("貓", "湯姆");
System.out.println(multimap.get("貓")); // [加菲, 湯姆]
HashMultimap 可以扔進去重復的 key 值,最后獲取時可以得到所有的 value 值,可以看到輸出結果和 JDK 寫法上是一樣的,但是代碼已經無比清爽。
字符串操作
作為開發中最常使用的數據類型,字符串操作的增強可以讓開發更加高效。
字符拼接
JDK 8 中其實已經內置了字符串拼接方法,但是它只是簡單的拼接,沒有額外操作,比如過濾掉 null 元素,去除前后空格等。先看一下 JDK 8 中字符串拼接的幾種方式。
// JDK 方式一
ArrayList<String> list = Lists.newArrayList("a", "b", "c", null);
String join = String.join(",", list);
System.out.println(join); // a,b,c,null
// JDK 方式二
String result = list.stream().collect(Collectors.joining(","));
System.out.println(result); // a,b,c,null
// JDK 方式三
StringJoiner stringJoiner = new StringJoiner(",");
list.forEach(stringJoiner::add);
System.out.println(stringJoiner.toString()); // a,b,c,null
可以看到 null 值也被拼接到了字符串里,這有時候不是我們想要的,那么使用 Guava 有什么不一樣呢?
ArrayList<String> list = Lists.newArrayList("a", "b", "c", null);
String join = Joiner.on(",").skipNulls().join(list);
System.out.println(join); // a,b,c
String join1 = Joiner.on(",").useForNull("空值").join("旺財", "湯姆", "杰瑞", null);
System.out.println(join1); // 旺財,湯姆,杰瑞,空值
可以看到使用 skipNulls() 可以跳過空值,使用 useFornull(String) 可以為空值自定義顯示文本。
字符串分割
JDK 中是自帶字符串分割的,我想你也一定用過,那就是 String 的 split 方法,但是這個方法有一個問題,就是如果最后一個元素為空,那么就會丟棄,奇怪的是第一個元素為空卻不會丟棄,這就十分迷惑,下面通過一個例子演示這個問題。
String str = ",a,,b,";
String[] splitArr = str.split(",");
Arrays.stream(splitArr).forEach(System.out::println);
System.out.println("------");
/**
*
* a
*
* b
* ------
*/
你也可以自己測試下,最后一個元素不是空,直接消失了。
如果使用 Guava 是怎樣的操作方式呢?Guava 提供了 Splitter 類,并且有一系列的操作方式可以直觀的控制分割邏輯。
String str = ",a ,,b ,";
Iterable<String> split = Splitter.on(",")
.omitEmptyStrings() // 忽略空值
.trimResults() // 過濾結果中的空白
.split(str);
split.forEach(System.out::println);
/**
* a
* b
*/
緩存
在開發中我們可能需要使用小規模的緩存,來提高訪問速度。這時引入專業的緩存中間件可能又覺得浪費。現在可以了, Guava 中提供了簡單的緩存類,且可以根據預計容量、過期時間等自動過期已經添加的元素。即使這樣我們也要預估好可能占用的內存空間,以防內存占用過多。
現在看一下在 Guava 中緩存該怎么用。
@Test
public void testCache() throws ExecutionException, InterruptedException {
CacheLoader cacheLoader = new CacheLoader<String, Animal>() {
// 如果找不到元素,會調用這里
@Override
public Animal load(String s) {
return null;
}
};
LoadingCache<String, Animal> loadingCache = CacheBuilder.newBuilder()
.maximumSize(1000) // 容量
.expireAfterWrite(3, TimeUnit.SECONDS) // 過期時間
.removalListener(new MyRemovalListener()) // 失效監聽器
.build(cacheLoader); //
loadingCache.put("狗", new Animal("旺財", 1));
loadingCache.put("貓", new Animal("湯姆", 3));
loadingCache.put("狼", new Animal("灰太狼", 4));
loadingCache.invalidate("貓"); // 手動失效
Animal animal = loadingCache.get("狼");
System.out.println(animal);
Thread.sleep(4 * 1000);
// 狼已經自動過去,獲取為 null 值報錯
System.out.println(loadingCache.get("狼"));
/**
* key=貓,value=Animal{name='湯姆', age=3},reason=EXPLICIT
* Animal{name='灰太狼', age=4}
* key=狗,value=Animal{name='旺財', age=1},reason=EXPIRED
* key=狼,value=Animal{name='灰太狼', age=4},reason=EXPIRED
*
* com.google.common.cache.CacheLoader$InvalidCacheLoadException: CacheLoader returned null for key 狼.
*/
}
/**
* 緩存移除監聽器
*/
class MyRemovalListener implements RemovalListener<String, Animal> {
@Override
public void onRemoval(RemovalNotification<String, Animal> notification) {
String reason = String.format("key=%s,value=%s,reason=%s", notification.getKey(), notification.getValue(), notification.getCause());
System.out.println(reason);
}
}
class Animal {
private String name;
private Integer age;
@Override
public String toString() {
return "Animal{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public Animal(String name, Integer age) {
this.name = name;
this.age = age;
}
}
這個例子中主要分為 CacheLoader、MyRemovalListener、LoadingCache。
CacheLoader 中重寫了 load 方法,這個方法會在查詢緩存沒有命中時被調用,我這里直接返回了 null ,其實這樣會在沒有命中時拋出 CacheLoader returned null for key 異常信息。
MyRemovalListener 作為緩存元素失效時的監聽類,在有元素緩存失效時會自動調用 onRemoval方法,這里需要注意的是這個方法是同步方法,如果這里耗時較長,會阻塞直到處理完成。
LoadingCache 就是緩存的主要操作對象了,常用的就是其中的 put 和 get 方法了。
總結
上面介紹了我認為最常用的 Guava 功能,Guava 作為 Google 公司開源的 Java 開發核心庫,個人覺得實用性還是很高的。引入后不僅能快速的實現一些開發中常用的功能,而且還可以讓代碼更加的優雅簡潔。我覺得適用于每一個 Java 項目。Guava 的其他的功能你也可以自己去發現。它的 Github 地址是:https://github.com/google/guava.