Google guava工具類的介紹和使用

小旋鋒發表於2018-08-30

概述

工具類 就是封裝平常用的方法,不需要你重複造輪子,節省開發人員時間,提高工作效率。谷歌作為大公司,當然會從日常的工作中提取中很多高效率的方法出來。所以就誕生了guava。

guava的優點:

  • 高效設計良好的API,被Google的開發者設計,實現和使用
  • 遵循高效的java語法實踐
  • 使程式碼更刻度,簡潔,簡單
  • 節約時間,資源,提高生產力

Guava工程包含了若干被Google的 Java專案廣泛依賴 的核心庫,例如:

  • 集合 [collections]
  • 快取 [caching]
  • 原生型別支援 [primitives support]
  • 併發庫 [concurrency libraries]
  • 通用註解 [common annotations]
  • 字串處理 [string processing]
  • I/O 等等。

這裡借用龍果學院深入淺出Guava課程的一張圖

龍果學院深入淺出Guava

使用

引入gradle依賴(引入Jar包)

compile 'com.google.guava:guava:26.0-jre'
複製程式碼

1.集合的建立

// 普通Collection的建立
List<String> list = Lists.newArrayList();
Set<String> set = Sets.newHashSet();
Map<String, String> map = Maps.newHashMap();

// 不變Collection的建立
ImmutableList<String> iList = ImmutableList.of("a", "b", "c");
ImmutableSet<String> iSet = ImmutableSet.of("e1", "e2");
ImmutableMap<String, String> iMap = ImmutableMap.of("k1", "v1", "k2", "v2");
複製程式碼

建立不可變集合 先理解什麼是immutable(不可變)物件

  • 在多執行緒操作下,是執行緒安全的
  • 所有不可變集合會比可變集合更有效的利用資源
  • 中途不可改變
ImmutableList<String> immutableList = ImmutableList.of("1","2","3","4");
複製程式碼

這宣告瞭一個不可變的List集合,List中有資料1,2,3,4。類中的 操作集合的方法(譬如add, set, sort, replace等)都被宣告過期,並且丟擲異常。 而沒用guava之前是需要宣告並且加各種包裹集合才能實現這個功能

  // add 方法
  @Deprecated @Override
  public final void add(int index, E element) {
    throw new UnsupportedOperationException();
  }
複製程式碼

當我們需要一個map中包含key為String型別,value為List型別的時候,以前我們是這樣寫的

Map<String,List<Integer>> map = new HashMap<String,List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
map.put("aa", list);
System.out.println(map.get("aa"));//[1, 2]
複製程式碼

而現在

Multimap<String,Integer> map = ArrayListMultimap.create();		
map.put("aa", 1);
map.put("aa", 2);
System.out.println(map.get("aa"));  //[1, 2]
複製程式碼

其他的黑科技集合

MultiSet: 無序+可重複   count()方法獲取單詞的次數  增強了可讀性+操作簡單
建立方式:  Multiset<String> set = HashMultiset.create();

Multimap: key-value  key可以重複  
建立方式: Multimap<String, String> teachers = ArrayListMultimap.create();

BiMap: 雙向Map(Bidirectional Map) 鍵與值都不能重複
建立方式:  BiMap<String, String> biMap = HashBiMap.create();

Table: 雙鍵的Map Map--> Table-->rowKey+columnKey+value  //和sql中的聯合主鍵有點像
建立方式: Table<String, String, Integer> tables = HashBasedTable.create();

...等等(guava中還有很多java裡面沒有給出的集合型別)
複製程式碼

2.將集合轉換為特定規則的字串

以前我們將list轉換為特定規則的字串是這樣寫的:

//use java
List<String> list = new ArrayList<String>();
list.add("aa");
list.add("bb");
list.add("cc");
String str = "";
for(int i=0; i<list.size(); i++){
	str = str + "-" +list.get(i);
}
//str 為-aa-bb-cc

//use guava
List<String> list = new ArrayList<String>();
list.add("aa");
list.add("bb");
list.add("cc");
String result = Joiner.on("-").join(list);
//result為  aa-bb-cc
複製程式碼

把map集合轉換為特定規則的字串

Map<String, Integer> map = Maps.newHashMap();
map.put("xiaoming", 12);
map.put("xiaohong",13);
String result = Joiner.on(",").withKeyValueSeparator("=").join(map);
// result為 xiaoming=12,xiaohong=13
複製程式碼

3.將String轉換為特定的集合

//use java
List<String> list = new ArrayList<String>();
String a = "1-2-3-4-5-6";
String[] strs = a.split("-");
for(int i=0; i<strs.length; i++){
	list.add(strs[i]);
}

//use guava
String str = "1-2-3-4-5-6";
List<String> list = Splitter.on("-").splitToList(str);
//list為  [1, 2, 3, 4, 5, 6]
複製程式碼

如果

str="1-2-3-4- 5-  6  ";
複製程式碼

guava還可以使用 omitEmptyStrings().trimResults() 去除空串與空格

String str = "1-2-3-4-  5-  6   ";  
List<String> list = Splitter.on("-").omitEmptyStrings().trimResults().splitToList(str);
System.out.println(list);
複製程式碼

將String轉換為map

String str = "xiaoming=11,xiaohong=23";
Map<String,String> map = Splitter.on(",").withKeyValueSeparator("=").split(str);
複製程式碼

4.guava還支援多個字元切割,或者特定的正則分隔

String input = "aa.dd,,ff,,.";
List<String> result = Splitter.onPattern("[.|,]").omitEmptyStrings().splitToList(input);
複製程式碼

關於字串的操作 都是在Splitter這個類上進行的

// 判斷匹配結果
boolean result = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z')).matches('K'); //true

// 保留數字文字  CharMatcher.digit() 已過時   retain 保留
//String s1 = CharMatcher.digit().retainFrom("abc 123 efg"); //123
String s1 = CharMatcher.inRange('0', '9').retainFrom("abc 123 efg"); // 123

// 刪除數字文字  remove 刪除
// String s2 = CharMatcher.digit().removeFrom("abc 123 efg");    //abc  efg
String s2 = CharMatcher.inRange('0', '9').removeFrom("abc 123 efg"); // abc  efg
複製程式碼

5. 集合的過濾

我們對於集合的過濾,思路就是迭代,然後再具體對每一個數判斷,這樣的程式碼放在程式中,難免會顯得很臃腫,雖然功能都有,但是很不好看。

guava寫法

//按照條件過濾
ImmutableList<String> names = ImmutableList.of("begin", "code", "Guava", "Java");
Iterable<String> fitered = Iterables.filter(names, Predicates.or(Predicates.equalTo("Guava"), Predicates.equalTo("Java")));
System.out.println(fitered); // [Guava, Java]

//自定義過濾條件   使用自定義回撥方法對Map的每個Value進行操作
ImmutableMap<String, Integer> m = ImmutableMap.of("begin", 12, "code", 15);
        // Function<F, T> F表示apply()方法input的型別,T表示apply()方法返回型別
        Map<String, Integer> m2 = Maps.transformValues(m, new Function<Integer, Integer>() {
            public Integer apply(Integer input) {
            	if(input>12){
            		return input;
            	}else{
            		return input+1;
            	}
            }
        });
System.out.println(m2);   //{begin=13, code=15}

複製程式碼

set的交集, 並集, 差集

HashSet setA = newHashSet(1, 2, 3, 4, 5);  
HashSet setB = newHashSet(4, 5, 6, 7, 8);  
   
SetView union = Sets.union(setA, setB);    
System.out.println("union:");  
for (Integer integer : union)  
    System.out.println(integer);           //union 並集:12345867
   
SetView difference = Sets.difference(setA, setB);  
System.out.println("difference:");  
for (Integer integer : difference)  
    System.out.println(integer);        //difference 差集:123
   
SetView intersection = Sets.intersection(setA, setB);  
System.out.println("intersection:");  
for (Integer integer : intersection)  
    System.out.println(integer);  //intersection 交集:45
複製程式碼

map的交集,並集,差集

HashMap<String, Integer> mapA = Maps.newHashMap();
mapA.put("a", 1);mapA.put("b", 2);mapA.put("c", 3);

HashMap<String, Integer> mapB = Maps.newHashMap();
mapB.put("b", 20);mapB.put("c", 3);mapB.put("d", 4);

MapDifference differenceMap = Maps.difference(mapA, mapB);
differenceMap.areEqual();
Map entriesDiffering = differenceMap.entriesDiffering();
Map entriesOnlyLeft = differenceMap.entriesOnlyOnLeft();
Map entriesOnlyRight = differenceMap.entriesOnlyOnRight();
Map entriesInCommon = differenceMap.entriesInCommon();

System.out.println(entriesDiffering);   // {b=(2, 20)}
System.out.println(entriesOnlyLeft);    // {a=1}
System.out.println(entriesOnlyRight);   // {d=4}
System.out.println(entriesInCommon);    // {c=3}
複製程式碼

6.檢查引數

//use java
if(list!=null && list.size()>0)
'''
if(str!=null && str.length()>0)
'''
if(str !=null && !str.isEmpty())

//use guava
if(!Strings.isNullOrEmpty(str))

//use java
if (count <= 0) {
    throw new IllegalArgumentException("must be positive: " + count);         
}    

//use guava
Preconditions.checkArgument(count > 0, "must be positive: %s", count);  
複製程式碼

免去了很多麻煩!並且會使你的程式碼看上去更好看。而不是程式碼裡面充斥著 !=null!=""

檢查是否為空,不僅僅是字串型別,其他型別的判斷,全部都封裝在 Preconditions類裡,裡面的方法全為靜態

其中的一個方法的原始碼

@CanIgnoreReturnValue
public static <T> T checkNotNull(T reference) {
    if (reference == null) {
      throw new NullPointerException();
    }
    return reference;
}
複製程式碼
方法宣告(不包括額外引數) 描述 檢查失敗時丟擲的異常
checkArgument(boolean) 檢查boolean是否為true,用來檢查傳遞給方法的引數。 IllegalArgumentException
checkNotNull(T) 檢查value是否為null,該方法直接返回value,因此可以內嵌使用checkNotNull。 NullPointerException
checkState(boolean) 用來檢查物件的某些狀態。 IllegalStateException
checkElementIndex(int index, int size) 檢查index作為索引值對某個列表、字串或陣列是否有效。 index > 0 && index < size IndexOutOfBoundsException
checkPositionIndexes(int start, int end, int size) 檢查[start,end]表示的位置範圍對某個列表、字串或陣列是否有效 IndexOutOfBoundsException

7. MoreObjects

這個方法是在Objects過期後官方推薦使用的替代品,該類最大的好處就是不用大量的重寫 toString,用一種很優雅的方式實現重寫,或者在某個場景定製使用。

Person person = new Person("aa",11);
String str = MoreObjects.toStringHelper("Person").add("age", person.getAge()).toString();
System.out.println(str);  
//輸出Person{age=11}
複製程式碼

8.強大的Ordering排序器

排序器[Ordering]是Guava流暢風格比較器[Comparator]的實現,它可以用來為構建複雜的比較器,以完成集合排序的功能。

natural()	對可排序型別做自然排序,如數字按大小,日期按先後排序
usingToString()	按物件的字串形式做字典排序[lexicographical ordering]
from(Comparator)	把給定的Comparator轉化為排序器
reverse()	獲取語義相反的排序器
nullsFirst()	使用當前排序器,但額外把null值排到最前面。
nullsLast()	使用當前排序器,但額外把null值排到最後面。
compound(Comparator)	合成另一個比較器,以處理當前排序器中的相等情況。
lexicographical()	基於處理型別T的排序器,返回該型別的可迭代物件Iterable<T>的排序器。
onResultOf(Function)	對集合中元素呼叫Function,再按返回值用當前排序器排序。
複製程式碼

示例

Person person = new Person("aa",14);  //String name  ,Integer age
Person ps = new Person("bb",13);
Ordering<Person> byOrdering = Ordering.natural().nullsFirst().onResultOf(new Function<Person,String>(){
	public String apply(Person person){
		return person.age.toString();
	}
});
byOrdering.compare(person, ps);
System.out.println(byOrdering.compare(person, ps)); //1      person的年齡比ps大 所以輸出1
複製程式碼

9.計算中間程式碼的執行時間

Stopwatch stopwatch = Stopwatch.createStarted();
for(int i=0; i<100000; i++){
	// do some thing
}
long nanos = stopwatch.elapsed(TimeUnit.MILLISECONDS);
System.out.println(nanos);
複製程式碼

TimeUnit 可以指定時間輸出精確到多少時間

10.檔案操作

以前我們寫檔案讀取的時候要定義緩衝區,各種條件判斷,各種 $%#$@#

而現在我們只需要使用好guava的api 就能使程式碼變得簡潔,並且不用擔心因為寫錯邏輯而背鍋了

File file = new File("test.txt");
List<String> list = null;
try {
	list = Files.readLines(file, Charsets.UTF_8);
} catch (Exception e) {
}

Files.copy(from,to);  //複製檔案
Files.deleteDirectoryContents(File directory); //刪除資料夾下的內容(包括檔案與子資料夾)  
Files.deleteRecursively(File file); //刪除檔案或者資料夾  
Files.move(File from, File to); //移動檔案
URL url = Resources.getResource("abc.xml"); //獲取classpath根下的abc.xml檔案url
複製程式碼

Files類中還有許多方法可以用,可以多多翻閱

11.guava快取

guava的快取設計的比較巧妙,可以很精巧的使用。guava快取建立分為兩種,一種是CacheLoader,另一種則是callback方式

CacheLoader:

LoadingCache<String,String> cahceBuilder=CacheBuilder
		        .newBuilder()
		        .build(new CacheLoader<String, String>(){
		            @Override
		            public String load(String key) throws Exception {        
		                String strProValue="hello "+key+"!";                
		                return strProValue;
		            }
		        });        
System.out.println(cahceBuilder.apply("begincode"));  //hello begincode!
System.out.println(cahceBuilder.get("begincode")); //hello begincode!
System.out.println(cahceBuilder.get("wen")); //hello wen!
System.out.println(cahceBuilder.apply("wen")); //hello wen!
System.out.println(cahceBuilder.apply("da"));//hello da!
cahceBuilder.put("begin", "code");
System.out.println(cahceBuilder.get("begin")); //code
複製程式碼

api中已經把apply宣告為過期,宣告中推薦使用get方法獲取值

callback方式:

 Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(1000).build();  
	        String resultVal = cache.get("code", new Callable<String>() {  
	            public String call() {  
	                String strProValue="begin "+"code"+"!";                
	                return strProValue;
	            }  
	        });  
 System.out.println("value : " + resultVal); //value : begin code!
複製程式碼

以上只是guava使用的一小部分,guava是個大的工具類,第一版guava是2010年釋出的,每一版的更新和迭代都是一種創新。

jdk的升級很多都是借鑑guava裡面的思想來進行的。

小結

程式碼可以在 github.com/whirlys/ela… 下載

細節請翻看 guava 文件 github.com/google/guav…

參考:
Google guava工具類的介紹和使用
Guava工具類學習


更多內容請訪問我的個人部落格:laijianfeng.org/

開啟微信掃一掃,關注【小旋鋒】微信公眾號,及時接收博文推送

小旋鋒的微信公眾號

相關文章