Google Guava
guava開源庫的位址:https://github.com/google/guava
概述
工具類 就是封裝平常用的方法,不需要你重複造輪子,節省開發人員時間,提高工作效率。谷歌作為大公司,當然會從日常的工作中提取中很多高效率的方法出來。是以就誕生了guava。
guava的優點:
- 高效設計良好的API,被Google的開發者設計,實作和使用
- 遵循高效的java文法實踐
- 使代碼更刻度,簡潔,簡單
- 節約時間,資源,提高生産力
guava的核心庫:
- 集合 [collections]
- 緩存 [caching]
- 原生類型支援 [primitives support]
- 并發庫 [concurrency libraries]
- 通用注解 [common annotations]
- 字元串處理 [string processing]
- I/O 等等。
一篇讓你熟練掌握Google Guava包(全網最全)Google Guava
guava的使用
引入gradle依賴(引入Jar包)
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
1.集合的建立
1.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(不可變)對象
- 在多線程操作下,是線程安全的
- 所有不可變集合會比可變集合更有效的利用資源
- 中途不可改變
這聲明了一個不可變的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();
}
1.2
當我們需要一個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]
1.3
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.特色工具
字元串連接配接器Joiner
連接配接多個字元串并追加到StringBuilder
StringBuilder stringBuilder = new StringBuilder("hello");
// 字元串連接配接器,以|為分隔符,同時去掉null元素
Joiner joiner1 = Joiner.on("|").skipNulls();
// 構成一個字元串foo|bar|baz并添加到stringBuilder
stringBuilder = joiner1.appendTo(stringBuilder, "foo", "bar", null, "baz");
System.out.println(stringBuilder); // hellofoo|bar|baz
連接配接List元素并寫到檔案流
FileWriter fileWriter = null;
try{
fileWriter = new FileWriter(new File("/home/gzx/Documents/tmp.txt"));
}
catch(Exception e){
System.out.println(e.getMessage());
}
List<Date> dateList = new ArrayList<Date>();
dateList.add(new Date());
dateList.add(null);
dateList.add(new Date());
// 構造連接配接器:如果有null元素,替換為no string
Joiner joiner2 = Joiner.on("#").useForNull("no string");
try{
// 将list的元素的tostring()寫到fileWriter,是否覆寫取決于fileWriter的打開方式,預設是覆寫,若有true,則是追加
joiner2.appendTo(fileWriter, dateList);
// 必須添加close(),否則不會寫檔案
fileWriter.close();
}
catch(IOException e){
System.out.println(e.getMessage());
}
字元串分割器Splitter
将字元串分割為Iterable
// 分割符為|,并去掉得到元素的前後空白
Splitter sp = Splitter.on("|").trimResults();
String str = "hello | world | your | Name ";
Iterable<String> ss = sp.split(str);
for(String it : ss){
System.out.println(it);
}
結果為:
hello
world
your
Name
字元串工具類Strings
System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true
System.out.println(Strings.isNullOrEmpty("hello")); // false
// 将null轉化為""
System.out.println(Strings.nullToEmpty(null)); // ""
// 從尾部不斷補充T隻到總共8個字元,如果源字元串已經達到或操作,則原樣傳回。類似的有padStart
System.out.println(Strings.padEnd("hello", 8, 'T')); // helloTTT
字元比對器CharMatcher
空白一一替換
// 空白回車換行對應換成一個#,一對一換
String stringWithLinebreaks = "hello world\r\r\ryou are here\n\ntake it\t\t\teasy";
String s6 = CharMatcher.BREAKING_WHITESPACE.replaceFrom(stringWithLinebreaks,'#');
System.out.println(s6); // hello#world###you#are#here##take#it###easy
連續空白縮成一個字元
// 将所有連在一起的空白回車換行字元換成一個#,倒塌
String tabString = " hello \n\t\tworld you\r\nare here ";
String tabRet = CharMatcher.WHITESPACE.collapseFrom(tabString, '#');
System.out.println(tabRet); // #hello#world#you#are#here#
去掉前後空白和縮成一個字元
// 在前面的基礎上去掉字元串的前後空白,并将空白換成一個#
String trimRet = CharMatcher.WHITESPACE.trimAndCollapseFrom(tabString, '#');
System.out.println(trimRet);// hello#world#you#are#here
保留數字
String letterAndNumber = "1234abcdABCD56789";
// 保留數字
String number = CharMatcher.JAVA_DIGIT.retainFrom(letterAndNumber);
System.out.println(number);// 123456789
3.将集合轉換為特定規則的字元串
3.1以前我們将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
3.2把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
4.将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]
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);
5.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
6. 集合的過濾
我們對于集合的過濾,思路就是疊代,然後再具體對每一個數判斷,這樣的代碼放在程式中,難免會顯得很臃腫,雖然功能都有,但是很不好看。
guava寫法
import com.google.common.base.*;
import com.google.common.collect.*;
import com.google.common.collect.Maps;
import org.junit.jupiter.api.Test;
import java.util.*;
/**
* @author: xingkong
* @date: 2020/11/18 10:26
* @description:
*/
public class Test8 {
@Test
public void Test1(){
//按照條件過濾
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, 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}
7.檢查參數
//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;
}
8. 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}
9.強大的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
10.計算中間代碼的運作時間
import com.google.common.base.Stopwatch;
import java.util.concurrent.TimeUnit;
/**
* @author: xingkong
* @date: 2020/11/18 20:16
* @description:
*/
public class Test9 {
public static void main(String[] args) throws InterruptedException {
// 建立stopwatch并開始計時
Stopwatch stopwatch = Stopwatch.createStarted();
Thread.sleep(1980);
// 以秒列印從計時開始至現在的所用時間,向下取整
System.out.println(stopwatch.elapsed(TimeUnit.SECONDS)); // 1
// 停止計時
stopwatch.stop();
System.out.println(stopwatch.elapsed(TimeUnit.SECONDS)); // 1
// 再次計時
stopwatch.start();
Thread.sleep(100);
System.out.println(stopwatch.elapsed(TimeUnit.SECONDS)); // 2
// 重置并開始
stopwatch.reset().start();
Thread.sleep(1030);
// 檢查是否運作
System.out.println(stopwatch.isRunning()); // true
long millis = stopwatch.elapsed(TimeUnit.MILLISECONDS); // 1034
System.out.println(millis);
// 列印
System.out.println(stopwatch.toString()); // 1.034 s
}
}
11.檔案操作
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
12.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方法擷取值