Guava工程包含了若干被Google的 Java項目廣泛依賴 的核心庫,例如:集合 [collections] 、緩存 [caching] 、原生類型支持 [primitives support] 、併發庫 [concurrency libraries] 、通用註解 [common annotations] 、字符串處理 [string processing] 、I/O 等等。使用guava可以讓你的java代碼更加的規範。具體使用:
如上圖所示,如果報錯,可以在maven中使用更早版本的guava包(錯誤意思是使用了1.8版本編譯但是不能用其他版本運行)
一、基本使用
1、使用和避免null
Optional.of(T):創建指定引用的Optional實例,若引用爲null則快速失敗;
Optional.absent():創建引用缺失的Optional實例;
Optional.fromNullable(T):創建指定引用的Optional實例,若引用爲null則表示缺失;
boolean isPresent():如果Optional包含非null的引用(引用存在),返回true;
T get():返回Optional所包含的引用,若引用缺失,則拋出java.lang.IllegalStateException;
@Test
public void optionalTest(){
Person p1 = new Person("周杰倫",37);
Person p2 = null;
Optional<Person> optPer1 = Optional.of(p1);
//Optional<Person> optPer2 = Optional.of(p2);//報空指針異常
Optional<Person> optPer2 = Optional.fromNullable(p2);//可以放空值
System.out.println(optPer1.get().getName());
//System.out.println(optPer2.get());//如果p2是空,使用formNullable,調用get則報java.lang.IllegalStateException: Optional.get() cannot be called on an absent value
System.out.println(optPer1.isPresent());//有值返回true
}
2、前置條件(讓方法調用的前置條件判斷更簡單)
checkArgument(i >= 0, “Argument was %s but expected nonnegative”, i);
checkNotNull(T)等方法;
@Test
public void testPreconditions(){
// 不會輸出任何代碼
String str = "abc";
Preconditions.checkNotNull(str,"str 爲 null");
//報java.lang.NullPointerException:constantName 爲 null
String constantName = null;
Preconditions.checkNotNull(constantName,"constantName 爲 null");
}
二、集合的使用
FluentIterable 是guava集合類中常用的一個類,主要用於過濾、轉換集合中的數據;FluentIterable 是一個抽象類,實現了Iterable接口,大多數方法都返回FluentIterable對象,這也是guava的思想之一。
return FluentIterable.from(results).transform(toPlanMinInvestAmountDTO()).toList();
private Function<Object[], PlanMinInvestAmountDTO> toPlanMinInvestAmountDTO() {
return new Function<Object[], PlanMinInvestAmountDTO>() {
@Override
public PlanMinInvestAmountDTO apply(Object[] input) {
return aPlanMinInvestAmountDTO()
.withMinInvestAmount((BigDecimal) input[0])
.withPlanType((String) input[1])
.build();
}
};
}
//測試過濾掉50歲以上的人
@Test
public void testFilter(){
Person p1 = new Person("周杰倫",37);
Person p2 = new Person("王力宏",43);
Person p3 = new Person("李易峯",23);
Person p4 = new Person("許鏡清",70);
Person p5 = new Person("貝多芬",72);
List<Person> persons = asList(p1, p2, p3,p4,p5);
List<Person> persons1 = from(persons).filter(getPersomAgeUnder30()).toList();
for(Person p:persons1){
System.out.println(p.getName()+" "+p.getAge());
}
}
//過濾大於50歲的,返回true則獲取該條數據到返回list中
private Predicate<Person> getPersomAgeUnder30() {
return new Predicate<Person>() {
public boolean apply(Person input) {
return input.age < 50;
}
};
}
三、函數式編程
過度使用Guava函數式編程會導致冗長、混亂、可讀性差而且低效的代碼。如上方法toPlanMinInvestAmountDTO
四、字符串處理:分割,連接
@Test
public void stringGuava(){
//連接器
Joiner joiner = Joiner.on(";").skipNulls();//如果不加skipNulls,參數中有null將會報空指針
System.out.println(joiner.join("Harry", null, "Ron", "Hermione"));//輸出Harry;Ron;Hermione
Joiner joiner2 = Joiner.on(";").useForNull("****");//代替null值
System.out.println(joiner2.join("Harry", null, "Ron", "Hermione"));//輸出Harry;****;Ron;Hermione
//拆分器
String str = ",a,,b,";
String[] strArr = str.split(",");
System.out.println(strArr.length);//輸出4
for(String s:strArr){
System.out.println(s==null? "NULL":s);//輸出"",a,"",b,只有尾部的空字符串被忽略
}
System.out.println("----------");
//omitEmptyStrings():從結果中自動忽略空字符串
//trimResults() :移除結果字符串的前導空白和尾部空白
//trimResults(CharMatcher):給定匹配器,移除結果字符串的前導匹配字符和尾部匹配字符
Iterable<String> strs = Splitter.on(",").trimResults().omitEmptyStrings().split(str);
for(String s:strs){
System.out.println(s);//只輸出a,b
}
//如果你想要拆分器返回List,只要使用Lists.newArrayList(splitter.split(string))或類似方法
}