Optional類
目的: 多用于返回值,明確null的語義,使用或者避免null
關(guān)鍵點: You (and others) are far more likely to forget that other.method(a, b) could return a null value than you're likely to forget that a could be null when you're implementing other.method.
- or(default T) 用默認值代替null
- isPresent() 判斷方法返回值, 函數(shù)式編程stream流的異常判斷
ArrayList<String> sList = new ArrayList<String>(16);
sList.add(null);
Optional<String> ops = Optional.fromNullable(sList.get(0));
ops.isPresent();
ops.of(null);
String def = "無";
System.out.println(ops.or(def));
Preconditions 類
應(yīng)用場景: 檢測方法參數(shù)或者運行方法時的狀態(tài)的合理性
方式: 在不滿足條件的情況下,拋出非受檢異,拋出IllegalArgumentException
IllegalStateException,NPE 等,給出對應(yīng)message
局限: 拋出均為包裝后的非受檢異常,無法捕獲處理,程序會終止
- Preconditions.checkArgument()
- Preconditions.checkState()
- Preconditions.checkNotNull()
private void arguementCheck(int i, int j){
Preconditions.checkArgument( i > j, "參數(shù)異常,期望參數(shù): i > j:傳入?yún)?shù) i:%s < j:%s ",i,j);
}
@Test
public void testArguement(){
arguementCheck(2,5);
}
Ordering 類(collect包)
應(yīng)用場景: 獲取多個最大最小值,多個比較,有序拷貝,反向,鏈式排序
- reverse()
- greatestOf()
- leastOf()
- List<> sortCopy()
- onResultOf(Function<T,R>)
private Ordering<People> nameOrder
= Ordering.natural().onResultOf(new Function<People,Integer>(){
@Override
public Integer apply(People p){
return p.height + p.weight;
}
});
@Test
public void testHeightWeightOrder(){
List<People> pl = Lists.newArrayList(
new People("ren",16,15),
new People("zhang",15,17),
new People("wang",17,13)
);
System.out.println(nameOrder.sortedCopy(pl));
System.out.println(nameOrder.reverse().sortedCopy(pl));
System.out.println(nameOrder.greatestOf(pl,2));
System.out.println(nameOrder.leastOf(pl,2));
}
MoreObject.ToStringHelper 類
應(yīng)用場景: key value格式化 toString()函數(shù)
- 構(gòu)造器 MoreObject.toStringHelper()
- add(String V value)
class People{
String name;
int height;
int weight;
public People(String name,int height,int weight){
this.name = name;
this.height = height;
this.weight = weight;
}
public String toString(){
return MoreObjects.toStringHelper(this)
.add("名字",name)
.add("身高",height)
.add("體重",weight)
.toString();
}
}
Splitter類
應(yīng)用場景: 條件分割,去除空格,去除空值
- on() 字符,字符串,Pattern
- trimResult()
- omitEmptyStrings()
- fixedLength()
- Iterable<> split()
- List<> splitToList()
@Test
public void testStringSplit(){
print(Splitter
.on("|")
.split("cat filename | grep '.*' || wc -l|"));
print(Splitter
.on("|")
.trimResults()
.split("cat filename || grep '.*' | wc -l|"));
print(Splitter
.on("|")
.trimResults()
.omitEmptyStrings()
.split("cat filename || grep '.*' | wc -l|"));
}
@Test
public void testImmutable(){
Splitter splitter = Splitter.on('/');
splitter.trimResults(); // does nothing!
// splitter = splitter.trimResults();
print(splitter.split("wrong / wrong / wrong"));
}