轉(zhuǎn)載 谷歌guava工具包詳解

概述

工具類 就是封裝平常用的方法抽碌,不需要你重復(fù)造輪子,節(jié)省開發(fā)人員時間决瞳,提高工作效率货徙。谷歌作為大公司左权,當(dāng)然會從日常的工作中提取中很多高效率的方法出來。所以就誕生了guava痴颊。

guava的優(yōu)點(diǎn):

高效設(shè)計良好的API赏迟,被Google的開發(fā)者設(shè)計,實(shí)現(xiàn)和使用

遵循高效的java語法實(shí)踐

使代碼更刻度祷舀,簡潔瀑梗,簡單

節(jié)約時間,資源裳扯,提高生產(chǎn)力

Guava工程包含了若干被Google的 Java項(xiàng)目廣泛依賴 的核心庫抛丽,例如:

集合 [collections]

緩存 [caching]

原生類型支持 [primitives support]

并發(fā)庫 [concurrency libraries]

通用注解 [common annotations]

字符串處理 [string processing]

I/O 等等。

使用

引入gradle依賴(引入Jar包)

compile'com.google.guava:guava:26.0-jre'

1.集合的創(chuàng)建

// 普通Collection的創(chuàng)建

List list = Lists.newArrayList();

Set set = Sets.newHashSet();

Map map = Maps.newHashMap();

// 不變Collection的創(chuàng)建

ImmutableList iList = ImmutableList.of("a","b","c");

ImmutableSet iSet = ImmutableSet.of("e1","e2");

ImmutableMap iMap = ImmutableMap.of("k1","v1","k2","v2");

創(chuàng)建不可變集合 先理解什么是immutable(不可變)對象

在多線程操作下饰豺,是線程安全的

所有不可變集合會比可變集合更有效的利用資源

中途不可改變

ImmutableList immutableList = ImmutableList.of("1","2","3","4");

這聲明了一個不可變的List集合亿鲜,List中有數(shù)據(jù)1,2冤吨,3蒿柳,4。類中的 操作集合的方法(譬如add, set, sort, replace等)都被聲明過期漩蟆,并且拋出異常垒探。 而沒用guava之前是需要聲明并且加各種包裹集合才能實(shí)現(xiàn)這個功能

// add 方法

@Deprecated@Override

publicfinalvoidadd(intindex, E element){

thrownewUnsupportedOperationException();

? }

當(dāng)我們需要一個map中包含key為String類型,value為List類型的時候怠李,以前我們是這樣寫的

Map> map =newHashMap>();

Listlist=newArrayList();

list.add(1);

list.add(2);

map.put("aa",list);

System.out.println(map.get("aa"));//[1, 2]

而現(xiàn)在

Multimapmap=ArrayListMultimap.create();

map.put("aa",1);

map.put("aa",2);

System.out.println(map.get("aa"));//[1, 2]

其他的黑科技集合

MultiSet: 無序+可重復(fù)? count()方法獲取單詞的次數(shù)? 增強(qiáng)了可讀性+操作簡單

創(chuàng)建方式:? Multiset set = HashMultiset.create();

Multimap: key-value? key可以重復(fù)?

創(chuàng)建方式: Multimap teachers = ArrayListMultimap.create();

BiMap: 雙向Map(BidirectionalMap) 鍵與值都不能重復(fù)

創(chuàng)建方式:? BiMap biMap = HashBiMap.create();

Table: 雙鍵的MapMap--> Table-->rowKey+columnKey+value//和sql中的聯(lián)合主鍵有點(diǎn)像

創(chuàng)建方式: Table tables = HashBasedTable.create();

...等等(guava中還有很多java里面沒有給出的集合類型)

2.將集合轉(zhuǎn)換為特定規(guī)則的字符串

以前我們將list轉(zhuǎn)換為特定規(guī)則的字符串是這樣寫的:

//use java

Listlist=newArrayList();

list.add("aa");

list.add("bb");

list.add("cc");

String str ="";

for(int i=0; i

str = str +"-"+list.get(i);

}

//str 為-aa-bb-cc

//use guava

Listlist=newArrayList();

list.add("aa");

list.add("bb");

list.add("cc");

String result = Joiner.on("-").join(list);

//result為? aa-bb-cc

把map集合轉(zhuǎn)換為特定規(guī)則的字符串

Mapmap=Maps.newHashMap();

map.put("xiaoming",12);

map.put("xiaohong",13);

Stringresult =Joiner.on(",").withKeyValueSeparator("=").join(map);

// result為 xiaoming=12,xiaohong=13

3.將String轉(zhuǎn)換為特定的集合

//use java

List list =newArrayList();

Stringa ="1-2-3-4-5-6";

String[] strs = a.split("-");

for(int i=0; i

? ? list.add(strs[i]);

}

//use guava

Stringstr ="1-2-3-4-5-6";

List list = Splitter.on("-").splitToList(str);

//list為? [1, 2, 3, 4, 5, 6]

如果

str="1-2-3-4- 5-? 6? ";


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

Stringstr ="1-2-3-4-? 5-? 6? ";

List list = Splitter.on("-").omitEmptyStrings().trimResults().splitToList(str);

System.out.println(list);

將String轉(zhuǎn)換為map

Stringstr ="xiaoming=11,xiaohong=23";

Map map = Splitter.on(",").withKeyValueSeparator("=").split(str);

4.guava還支持多個字符切割圾叼,或者特定的正則分隔

Stringinput ="aa.dd,,ff,,.";

List result = Splitter.onPattern("[.|,]").omitEmptyStrings().splitToList(input);

關(guān)于字符串的操作 都是在Splitter這個類上進(jìn)行的

// 判斷匹配結(jié)果

booleanresult = CharMatcher.inRange('a','z').or(CharMatcher.inRange('A','Z')).matches('K');//true

// 保留數(shù)字文本? CharMatcher.digit() 已過時? retain 保留

//String s1 = CharMatcher.digit().retainFrom("abc 123 efg"); //123

String s1 = CharMatcher.inRange('0','9').retainFrom("abc 123 efg");// 123

// 刪除數(shù)字文本? remove 刪除

// String s2 = CharMatcher.digit().removeFrom("abc 123 efg");? ? //abc? efg

String s2 = CharMatcher.inRange('0','9').removeFrom("abc 123 efg");// abc? efg

5. 集合的過濾

我們對于集合的過濾,思路就是迭代捺癞,然后再具體對每一個數(shù)判斷夷蚊,這樣的代碼放在程序中,難免會顯得很臃腫髓介,雖然功能都有惕鼓,但是很不好看。

guava寫法

//按照條件過濾

ImmutableList names = ImmutableList.of("begin","code","Guava","Java");

Iterable fitered = Iterables.filter(names, Predicates.or(Predicates.equalTo("Guava"), Predicates.equalTo("Java")));

System.out.println(fitered);// [Guava, Java]

//自定義過濾條件? 使用自定義回調(diào)方法對Map的每個Value進(jìn)行操作

ImmutableMap m = ImmutableMap.of("begin",12,"code",15);

// Function<F, T> F表示apply()方法input的類型唐础,T表示apply()方法返回類型

Map m2 = Maps.transformValues(m,newFunction() {

publicIntegerapply(Integer input){

if(input>12){

returninput;

}else{

returninput+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.檢查參數(shù)

//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) {

thrownewIllegalArgumentException("must be positive: "+ count);

}? ?

//use guava

Preconditions.checkArgument(count >0,"must be positive: %s", count);

免去了很多麻煩一膨!并且會使你的代碼看上去更好看呀邢。而不是代碼里面充斥著!=null,!=""

檢查是否為空,不僅僅是字符串類型汞幢,其他類型的判斷,全部都封裝在 Preconditions類里微谓,里面的方法全為靜態(tài)

其中的一個方法的源碼

@CanIgnoreReturnValue

publicstaticTcheckNotNull(T reference){

if(reference ==null) {

thrownewNullPointerException();

? ? }

returnreference;

}

方法聲明(不包括額外參數(shù))描述檢查失敗時拋出的異常

checkArgument(boolean)檢查boolean是否為true森篷,用來檢查傳遞給方法的參數(shù)输钩。IllegalArgumentException

checkNotNull(T)檢查value是否為null,該方法直接返回value仲智,因此可以內(nèi)嵌使用checkNotNull买乃。NullPointerException

checkState(boolean)用來檢查對象的某些狀態(tài)。IllegalStateException

checkElementIndex(int index, int size)檢查index作為索引值對某個列表钓辆、字符串或數(shù)組是否有效剪验。 index > 0 && index < sizeIndexOutOfBoundsException

checkPositionIndexes(int start, int end, int size)檢查[start,end]表示的位置范圍對某個列表、字符串或數(shù)組是否有效IndexOutOfBoundsException

7. MoreObjects

這個方法是在Objects過期后官方推薦使用的替代品前联,該類最大的好處就是不用大量的重寫toString功戚,用一種很優(yōu)雅的方式實(shí)現(xiàn)重寫,或者在某個場景定制使用似嗤。

Person person =newPerson("aa",11);

String str = MoreObjects.toStringHelper("Person").add("age", person.getAge()).toString();

System.out.println(str);

//輸出Person{age=11}

8.強(qiáng)大的Ordering排序器

排序器[Ordering]是Guava流暢風(fēng)格比較器[Comparator]的實(shí)現(xiàn)啸臀,它可以用來為構(gòu)建復(fù)雜的比較器,以完成集合排序的功能烁落。

natural()? 對可排序類型做自然排序乘粒,如數(shù)字按大小,日期按先后排序

usingToString() 按對象的字符串形式做字典排序[lexicographical ordering]

from(Comparator)? ? 把給定的Comparator轉(zhuǎn)化為排序器

reverse()? 獲取語義相反的排序器

nullsFirst()? ? 使用當(dāng)前排序器伤塌,但額外把null值排到最前面灯萍。

nullsLast() 使用當(dāng)前排序器,但額外把null值排到最后面每聪。

compound(Comparator)? ? 合成另一個比較器旦棉,以處理當(dāng)前排序器中的相等情況。

lexicographical()? 基于處理類型T的排序器熊痴,返回該類型的可迭代對象Iterable<T>的排序器他爸。

onResultOf(Function)? ? 對集合中元素調(diào)用Function,再按返回值用當(dāng)前排序器排序果善。

示例

Person person =newPerson("aa",14);//String name? ,Integer age

Person ps =newPerson("bb",13);

Ordering byOrdering = Ordering.natural().nullsFirst().onResultOf(newFunction(){

publicStringapply(Person person){

returnperson.age.toString();

? ? }

});

byOrdering.compare(person, ps);

System.out.println(byOrdering.compare(person, ps));//1? ? ? person的年齡比ps大 所以輸出1

9.計算中間代碼的運(yùn)行時間

Stopwatch stopwatch = Stopwatch.createStarted();

for(inti=0; i<100000; i++){

// do some thing

}

longnanos = stopwatch.elapsed(TimeUnit.MILLISECONDS);

System.out.println(nanos);

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

10.文件操作

以前我們寫文件讀取的時候要定義緩沖區(qū)诊笤,各種條件判斷,各種$%#$@#

而現(xiàn)在我們只需要使用好guava的api 就能使代碼變得簡潔巾陕,并且不用擔(dān)心因?yàn)閷戝e邏輯而背鍋了

File file =newFile("test.txt");

List list =null;

try{

? ? list = Files.readLines(file, Charsets.UTF_8);

}catch(Exception e) {

}

Files.copy(from,to);//復(fù)制文件

Files.deleteDirectoryContents(File directory);//刪除文件夾下的內(nèi)容(包括文件與子文件夾)?

Files.deleteRecursively(File file);//刪除文件或者文件夾?

Files.move(File from, File to);//移動文件

URL url = Resources.getResource("abc.xml");//獲取classpath根下的abc.xml文件url

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

11.guava緩存

guava的緩存設(shè)計的比較巧妙,可以很精巧的使用鄙煤。guava緩存創(chuàng)建分為兩種晾匠,一種是CacheLoader,另一種則是callback方式

Cache的定時清理實(shí)現(xiàn)邏輯(失效時間+增加維護(hù)accessQueue,writeQueue兩個隊列用于記錄緩存順序,這樣才可以按照順序淘汰數(shù)據(jù)):https://crossoverjie.top/2018/06/13/guava/guava-cache/

CacheLoader:

LoadingCache<String,String> cahceBuilder=CacheBuilder

? ? ? ? ? ? ? ? .newBuilder()

// 設(shè)置并發(fā)級別梯刚,并發(fā)級別是指可以同時寫緩存的線程數(shù)

.concurrencyLevel(10)

// 設(shè)置緩存過期時間

.expireAfterWrite(10, TimeUnit.MINUTES)

// 設(shè)置緩存容器的初始容量

.initialCapacity(10)

// 設(shè)置緩存最大容量凉馆,超過之后就會按照LRU最近雖少使用算法來移除緩存項(xiàng)

.maximumSize(500)

// 設(shè)置緩存的移除通知

.removalListener(newRemovalListener() {

publicvoidonRemoval(RemovalNotification<Object, Object> notification){

LOGGER.warn(notification.getKey() +" was removed, cause is "+ notification.getCause());

? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? })

.build(newCacheLoader(){

@Override

publicStringload(String key)throwsException{

String strProValue="hello "+key+"!";

returnstrProValue;

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? });? ? ? ?

System.out.println(cahceBuilder.apply("begincode"));//hello begincode!

System.out.println(cahceBuilder.get("begincode"));//hello begincode!

System.out.println(cahceBuilder.get("wen"));//hello wen!? ? //獲取緩存值,callable實(shí)現(xiàn)緩存回調(diào)

System.out.println(cahceBuilder.apply("wen"));//hello wen!? //請求緩存值

System.out.println(cahceBuilder.apply("da"));//hello da!

cahceBuilder.put("begin","code");//設(shè)置緩存內(nèi)容

System.out.println(cahceBuilder.get("begin"));//code

cahceBuilder.invalidateAll();//清除緩存

api中已經(jīng)把a(bǔ)pply聲明為過期,聲明中推薦使用get方法獲取值

callback方式: 回調(diào)之中已經(jīng)實(shí)現(xiàn)了對數(shù)據(jù)的添加澜共,

Cache cache = CacheBuilder.newBuilder().maximumSize(1000).build();

String resultVal = cache.get("code",newCallable() {

publicStringcall(){

String strProValue="begin "+"code"+"!";//回調(diào)實(shí)現(xiàn)添加入值向叉;無需put?

returnstrProValue;

? ? }?

});?

System.out.println("value : "+ resultVal);//value : begin code!

//get回調(diào)實(shí)現(xiàn)源碼

Vget(K key,inthash, CacheLoader loader)throwsExecutionException{

? ? ? checkNotNull(key);

? ? ? checkNotNull(loader);

try{

if(count !=0) {// read-volatile

// don't call getLiveEntry, which would ignore loading values

? ? ? ? ? ReferenceEntry<K, V> e = getEntry(key, hash);

if(e !=null) {

longnow = map.ticker.read();

? ? ? ? ? ? V value = getLiveValue(e, now);

if(value !=null) {

? ? ? ? ? ? ? recordRead(e, now);

statsCounter.recordHits(1);

returnscheduleRefresh(e, key, hash, value, now, loader);

? ? ? ? ? ? }

? ? ? ? ? ? ValueReference<K, V> valueReference = e.getValueReference();

if(valueReference.isLoading()) {

returnwaitForLoadingValue(e, key, valueReference);

? ? ? ? ? ? }

? ? ? ? ? }

? ? ? ? }

// 緩存中不存在數(shù)據(jù)

returnlockedGetOrLoad(key, hash, loader);

}catch(ExecutionException ee) {

? ? ? ? Throwable cause = ee.getCause();

if(causeinstanceofError) {

thrownewExecutionError((Error) cause);

}elseif(causeinstanceofRuntimeException) {

thrownewUncheckedExecutionException(cause);

? ? ? ? }

throwee;

}finally{

? ? ? ? postReadCleanup();

? ? ? }

? ? }

以上只是guava使用的一小部分,guava是個大的工具類嗦董,第一版guava是2010年發(fā)布的母谎,每一版的更新和迭代都是一種創(chuàng)新。

jdk的升級很多都是借鑒guava里面的思想來進(jìn)行的京革。

小結(jié)

代碼可以在https://github.com/whirlys/elastic-example/tree/master/guava下載

細(xì)節(jié)請翻看 guava 文檔https://github.com/google/guava/wiki

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末奇唤,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子匹摇,更是在濱河造成了極大的恐慌咬扇,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,729評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件来惧,死亡現(xiàn)場離奇詭異冗栗,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)供搀,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,226評論 3 399
  • 文/潘曉璐 我一進(jìn)店門隅居,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人葛虐,你說我怎么就攤上這事胎源。” “怎么了屿脐?”我有些...
    開封第一講書人閱讀 169,461評論 0 362
  • 文/不壞的土叔 我叫張陵涕蚤,是天一觀的道長。 經(jīng)常有香客問我的诵,道長万栅,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,135評論 1 300
  • 正文 為了忘掉前任西疤,我火速辦了婚禮烦粒,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘代赁。我一直安慰自己扰她,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,130評論 6 398
  • 文/花漫 我一把揭開白布芭碍。 她就那樣靜靜地躺著徒役,像睡著了一般。 火紅的嫁衣襯著肌膚如雪窖壕。 梳的紋絲不亂的頭發(fā)上忧勿,一...
    開封第一講書人閱讀 52,736評論 1 312
  • 那天杉女,我揣著相機(jī)與錄音,去河邊找鬼鸳吸。 笑死宠纯,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的层释。 我是一名探鬼主播,決...
    沈念sama閱讀 41,179評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼快集,長吁一口氣:“原來是場噩夢啊……” “哼贡羔!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起个初,我...
    開封第一講書人閱讀 40,124評論 0 277
  • 序言:老撾萬榮一對情侶失蹤乖寒,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后院溺,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體楣嘁,經(jīng)...
    沈念sama閱讀 46,657評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,723評論 3 342
  • 正文 我和宋清朗相戀三年珍逸,在試婚紗的時候發(fā)現(xiàn)自己被綠了逐虚。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,872評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡谆膳,死狀恐怖叭爱,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情漱病,我是刑警寧澤买雾,帶...
    沈念sama閱讀 36,533評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站杨帽,受9級特大地震影響漓穿,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜注盈,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,213評論 3 336
  • 文/蒙蒙 一晃危、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧当凡,春花似錦山害、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,700評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至朴则,卻和暖如春权纤,著一層夾襖步出監(jiān)牢的瞬間钓简,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,819評論 1 274
  • 我被黑心中介騙來泰國打工汹想, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留外邓,地道東北人。 一個月前我還...
    沈念sama閱讀 49,304評論 3 379
  • 正文 我出身青樓古掏,卻偏偏與公主長得像损话,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子槽唾,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,876評論 2 361

推薦閱讀更多精彩內(nèi)容