概述
工具類 就是封裝平常用的方法以躯,不需要你重復(fù)造輪子槐秧,節(jié)省開發(fā)人員時(shí)間,提高工作效率忧设。谷歌作為大公司刁标,當(dāng)然會(huì)從日常的工作中提取中很多高效率的方法出來(lái)。所以就誕生了guava见转。命雀。
- 高效設(shè)計(jì)良好的API,被Google的開發(fā)者設(shè)計(jì)斩箫,實(shí)現(xiàn)和使用
- 遵循高效的java語(yǔ)法實(shí)踐
- 使代碼更刻度吏砂,簡(jiǎn)潔,簡(jiǎn)單
- 節(jié)約時(shí)間乘客,資源狐血,提高生產(chǎn)力
Guava工程包含了若干被Google的 Java項(xiàng)目廣泛依賴 的核心庫(kù),例如:
- 集合 [collections]
- 緩存 [caching]
- 原生類型支持 [primitives support]
- 并發(fā)庫(kù) [concurrency libraries]
- 通用注解 [common annotations]
- 字符串處理 [string processing]
- I/O 等等易核。
使用
引入maven依賴(就是引入jar包)
(從版本號(hào)就能看出 guava是一步步改進(jìn)的匈织,并且跟隨的jdk不斷的提取其中優(yōu)秀的部分)
'''
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
'''
1.集合的創(chuàng)建
// 普通Collection的創(chuàng)建
List<String> list = Lists.newArrayList();
Set<String> set = Sets.newHashSet();
Map<String, String> map = Maps.newHashMap();
// 不變Collection的創(chuàng)建
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");
創(chuàng)建不可變集合 先理解什么是immutable(不可變)對(duì)象
1.在多線程操作下,是線程安全的牡直。
2.所有不可變集合會(huì)比可變集合更有效的利用資源缀匕。
3.中途不可改變
ImmutableList<String> immutableList = ImmutableList.of("1","2","3","4");
這句話就聲明了一個(gè)不可變的list集合,里面有數(shù)據(jù)1碰逸,2乡小,3,4饵史。方法中的==操作集合的方法都聲明過期==满钟,并且拋出異常。
沒用guava之前是需要聲明并且加各種包裹集合才能實(shí)現(xiàn)這個(gè)功能胳喷。
當(dāng)我們需要一個(gè)map中包含key為String value為L(zhǎng)ist類型的時(shí)候 以前我們是這樣寫的
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]
而現(xiàn)在
Multimap<String,Integer> map = ArrayListMultimap.create();
map.put("aa", 1);
map.put("aa", 2);
System.out.println(map.get("aa")); //[1, 2]
其他的黑科技集合
MultiSet: 無(wú)序+可重復(fù) count()方法獲取單詞的次數(shù) 增強(qiáng)了可讀性+操作簡(jiǎn)單
創(chuàng)建方式: Multiset<String> set = HashMultiset.create();
Multimap: key-value key可以重復(fù)
創(chuàng)建方式: Multimap<String, String> teachers = ArrayListMultimap.create();
BiMap: 雙向Map(Bidirectional Map) 鍵與值都不能重復(fù)
創(chuàng)建方式: BiMap<String, String> biMap = HashBiMap.create();
Table: 雙鍵的Map Map--> Table-->rowKey+columnKey+value //和sql中的聯(lián)合主鍵有點(diǎn)像
創(chuàng)建方式: Table<String, String, Integer> tables = HashBasedTable.create();
...等等(guava中還有很多java里面沒有給出的集合類型)
2.將集合轉(zhuǎn)換為特定規(guī)則的字符串
以前我們將list轉(zhuǎn)換為特定規(guī)則的字符串是這樣寫的:
//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集合轉(zhuǎn)換為特定規(guī)則的字符串
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轉(zhuǎn)換為特定的集合
//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轉(zhuǎn)換為map
String str = "xiaoming=11,xiaohong=23";
Map<String,String> map = Splitter.on(",").withKeyValueSeparator("=").split(str);
4.guava還支持多個(gè)字符切割湃番,或者特定的正則分隔
String input = "aa.dd,,ff,,.";
List<String> result = Splitter.onPattern("[.|,]").omitEmptyStrings().splitToList(input);
==關(guān)于字符串的操作 都是在Splitter這個(gè)類上進(jìn)行的。==
// 判斷匹配結(jié)果
boolean result = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z')).matches('K'); //true
// 保留數(shù)字文本
String s1 = CharMatcher.digit().retainFrom("abc 123 efg"); //123
// 刪除數(shù)字文本
String s2 = CharMatcher.digit().removeFrom("abc 123 efg"); //abc efg
5. 集合的過濾
我們對(duì)于集合的過濾吭露,思路就是迭代吠撮,然后再具體對(duì)每一個(gè)數(shù)判斷,這樣的代碼放在程序中讲竿,難免會(huì)顯得很臃腫泥兰,雖然功能都有择浊,但是很不好看。
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]
//自定義過濾條件 使用自定義回調(diào)方法對(duì)Map的每個(gè)Value進(jìn)行操作
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的交集琢岩,并集,差集
MapDifference differenceMap = Maps.difference(mapA, mapB);
differenceMap.areEqual();
Map entriesDiffering = differenceMap.entriesDiffering();
Map entriesOnlyOnLeft = differenceMap.entriesOnlyOnLeft();
Map entriesOnlyOnRight = differenceMap.entriesOnlyOnRight();
Map entriesInCommon = differenceMap.entriesInCommon();
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) {
throw new IllegalArgumentException("must be positive: " + count);
}
//use guava
Preconditions.checkArgument(count > 0, "must be positive: %s", count);
免去了很多麻煩师脂!并且會(huì)使你的代碼看上去更好看担孔。而不是代碼里面充斥著!=null, !=""
(問答系統(tǒng)源碼里面有很多這種代碼吃警,后一版得抓緊改掉糕篇。。)
檢查是否為空,不僅僅是字符串類型酌心,其他類型的判斷 全部都封裝在 Preconditions類里 里面的方法全為靜態(tài)拌消。
其中的一個(gè)方法的源碼
@CanIgnoreReturnValue
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
方法聲明(不包括額外參數(shù)) | 描述 | 檢查失敗時(shí)拋出的異常 |
---|---|---|
checkArgument(boolean) | 檢查boolean是否為true,用來(lái)檢查傳遞給方法的參數(shù)安券。 | IllegalArgumentException |
checkNotNull(T) | 檢查value是否為null墩崩,該方法直接返回value,因此可以內(nèi)嵌使用checkNotNull侯勉。 | NullPointerException |
checkState(boolean) | 用來(lái)檢查對(duì)象的某些狀態(tài)鹦筹。 | IllegalStateException |
checkElementIndex(int index, int size) | 檢查index作為索引值對(duì)某個(gè)列表、字符串或數(shù)組是否有效址貌。index>=0 && index<size * | IndexOutOfBoundsException |
checkPositionIndexes(int start, int end, int size) | 檢查[start, end]表示的位置范圍對(duì)某個(gè)列表铐拐、字符串或數(shù)組是否有效* | IndexOutOfBoundsException |
7.MoreObjects
這個(gè)方法是在Objects過期后 官方推薦使用的替代品,該類最大的好處就是不用大量的重寫toString练对,用一種很優(yōu)雅的方式實(shí)現(xiàn)重寫遍蟋,或者在某個(gè)場(chǎng)景定制使用。
Person person = new Person("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)螟凭,它可以用來(lái)為構(gòu)建復(fù)雜的比較器虚青,以完成集合排序的功能。
natural() 對(duì)可排序類型做自然排序赂摆,如數(shù)字按大小挟憔,日期按先后排序
usingToString() 按對(duì)象的字符串形式做字典排序[lexicographical ordering]
from(Comparator) 把給定的Comparator轉(zhuǎn)化為排序器
reverse() 獲取語(yǔ)義相反的排序器
nullsFirst() 使用當(dāng)前排序器钟些,但額外把null值排到最前面烟号。
nullsLast() 使用當(dāng)前排序器,但額外把null值排到最后面政恍。
compound(Comparator) 合成另一個(gè)比較器汪拥,以處理當(dāng)前排序器中的相等情況。
lexicographical() 基于處理類型T的排序器篙耗,返回該類型的可迭代對(duì)象Iterable<T>的排序器迫筑。
onResultOf(Function) 對(duì)集合中元素調(diào)用Function宪赶,再按返回值用當(dāng)前排序器排序。
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.計(jì)算中間代碼的運(yùn)行時(shí)間
Stopwatch stopwatch = Stopwatch.createStarted();
for(int i=0; i<100000; i++){
}
long nanos = stopwatch.elapsed(TimeUnit.MILLISECONDS);
System.out.println(nanos);
TimeUnit 可以指定時(shí)間輸出精確到多少時(shí)間
10.文件操作
以前我們寫文件讀取的時(shí)候要定義緩沖區(qū)脯燃,各種條件判斷搂妻,各種@#
而現(xiàn)在我們只需要使用好guava的api 就能使代碼變得簡(jiǎn)潔,并且不用擔(dān)心因?yàn)閷戝e(cuò)邏輯而背鍋了
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); //復(fù)制文件
Files.deleteDirectoryContents(File directory); //刪除文件夾下的內(nèi)容(包括文件與子文件夾)
Files.deleteRecursively(File file); //刪除文件或者文件夾
Files.move(File from, File to); //移動(dòng)文件
URL url = Resources.getResource("abc.xml"); //獲取classpath根下的abc.xml文件url
Files類中還有許多方法可以用辕棚,可以多多翻閱欲主。
11.guava緩存
guava的緩存設(shè)計(jì)的比較巧妙,可以很精巧的使用逝嚎。guava緩存創(chuàng)建分為兩種扁瓢,一種是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中已經(jīng)把a(bǔ)pply聲明為過期,聲明中推薦使用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是個(gè)大的工具類引几,第一版guava是2010年發(fā)布的,每一版的更新和迭代都是一種創(chuàng)新挽铁。