當前位置:
首頁 > 知識 > Google Guava 筆記(二)-深入探索

Google Guava 筆記(二)-深入探索


關注「教授學苑」,期待帶給你快樂的開發知識!

Google Guava 筆記(二)-深入探索

接上篇Google Guava Collections

本篇將深入挖掘Guava庫,並了解一下優雅的CharMatcher類、Joiner以及Splitter類,以及在處理Java基本類型時Guava給我們帶來的別的工具類


The Guava CharMatcher

正則的處理一直都可以被稱為為巫術,不能很好的掌握。而Guava 中的CharMatcher有人形容它:「像打了興奮劑的StringUtils」:比如你可以使用預先設定好的常量,比如CharMatcher.WHITESPACE, CharMatcher.JAVA_DIGIT 或者CharMatcher.ASCII,此外你還有很多簡便的工廠方法如CharMatcher.is(『aaa』), CharMatcher.isNot(『bbb』), CharMatcher.oneOf(『abcd』).negate(),甚至更複雜一些像:

Google Guava 筆記(二)-深入探索

如果你想從字元串中得到所有的數字,可以這樣:

Google Guava 筆記(二)-深入探索

如果你想把字元串中的數據都去掉,可以這樣:

Google Guava 筆記(二)-深入探索

還有好多牛逼的方法:

Google Guava 筆記(二)-深入探索


Joiner and Splitter

java JDK 本身的splitter 相對Google Guava的那就要弱很多了。

對於字元串,我們可以直接進行分割,但 Splitter 提供了更多的操作,而且更加健壯。字元創分割通常返回的是一個數組而 Splitter 返回的是一個迭代 Iterable。

Google Guava 筆記(二)-深入探索

Google Guava 筆記(二)-深入探索

當面對更複雜情況時,比如提取下面的foor,what more.?

Google Guava 筆記(二)-深入探索

Splitter允許我們對分割結果做更多的控制:

Google Guava 筆記(二)-深入探索

得到的結果是 foo』,"what』,"more』,有沒有爽到哭的感覺?

再來看一下Joiner,你可以扔掉Stringbuilder了。

Google Guava 筆記(二)-深入探索

Google Guava 筆記(二)-深入探索

由於Guava對基本型的支持很強大,可以很方便:

Google Guava 筆記(二)-深入探索

對於字元串,我們可以直接進行分割,但是這樣做多少有些奇怪, Splitter 提供了更多的操作,而且更加健壯。字元創分割通常返回的是一個數組而 Splitter 返回的是一個迭代 Iterable

Google Guava 筆記(二)-深入探索

也可以簡單地分割字元串:

Google Guava 筆記(二)-深入探索

當需要處理下面這樣的字元串時:

Google Guava 筆記(二)-深入探索

輸出結果是:

Google Guava 筆記(二)-深入探索

plitter允許我們對分割結果做更多的控制:

Google Guava 筆記(二)-深入探索

得到的結果是 foo』,"what』,"more』

Joiner和Splitter都是可配置的,甚至你可以把Joiner使用在map中。

最後再看個幾個例子吧:

Google Guava 筆記(二)-深入探索

Google Guava 筆記(二)-深入探索

Google Guava 筆記(二)-深入探索

Google Guava 筆記(二)-深入探索

Google Guava 筆記(二)-深入探索

Google Guava 筆記(二)-深入探索

Google Guava 筆記(二)-深入探索


關注「教授學苑」,期待帶給你快樂的開發知識!

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 教授學苑 的精彩文章:

Google Guava 筆記(一)-Collections
JavaScript 代碼規範,自帶 linter & 代碼自動修正
JavaScript 之Array 你真的了解嗎?

TAG:教授學苑 |

您可能感興趣

Greenlight深入分析Oculus Go的消費者認知
深入解讀Google Lens
深入 JVM 分析 spring-boot 應用 hibernate-validatorNoClassDefFoundError
深入 git rebase
深入GlobalFoundries的晶元前沿領域探索之路
深入 Spring Boot :實現對 Fat Jar jsp 的支持
三星GalaxyBuds深入體驗報告附對比榮耀flypods
深入近賞劃時代手機 Samsung Galaxy Fold
深入 SpringBoot : 怎樣排查 expectedsinglematchingbeanbutfound 2 的異常
Glibc堆漏洞利用基礎-深入理解ptmalloc2 part1
文獻 深入探尋Grotowski
MapReduce Shuffle深入理解
convergencias展覽 深入探索古巴設計
「深入探討Xbox One X優化」萬代南夢宮&Arc System Works談《龍珠戰士Z》
「深入探討Xbox One劇情類遊戲創作」MachineGames談《德軍總部》
Node.js進階:cluster模塊深入剖析
async/await使用深入詳解
「深入探討Xbox One X優化」Slightly Mad工作室談《賽車計劃2》
深入理解 ES Modules
深入分析利用宏代碼傳播NetwiredRC和Quasar RAT的惡意RTF文檔