[toc]
guava: google 的開(kāi)源工具包
幫助編寫常用方法
hashCode缤沦,equals,toString,compareTo方法掀抹;前三個(gè)idea 提供了guava方式的代碼生成
import com.google.common.base.MoreObjects;
import com.google.common.collect.ComparisonChain;
public class User implements Comparable<User>{
private String name;
private int age;
//omit setting and getting
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return age == user.age &&
com.google.common.base.Objects.equal(name, user.name);
}
@Override
public int hashCode() {
return com.google.common.base.Objects.hashCode(name, age);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("name", name)
.add("age", age)
.toString();
}
@Override
public int compareTo(User other) {
return ComparisonChain.start().
compare(this.name,other.name).
compare(this.age,other.age).
result();
}
}
檢查方法調(diào)用的前置條件
一般盡快失敗來(lái)拒絕不符合條件的調(diào)用
private void addAge(User user,int age){
//檢查非空滔悉, throw NullPointerException
Preconditions.checkNotNull(user,"%s must not be null","user");
//檢查參數(shù)伊诵,throw IllegalArgumentException
Preconditions.checkArgument(age>0,"the %s should greater than 0; now: %s","age",age);
//檢查對(duì)象的狀態(tài),throw IllegalStateException
Preconditions.checkState(user.getAge()>10,"the age of %s should larger than 10; now: %s",user.getName(),2);
//檢查index作為索引值對(duì)某個(gè)列表、字符串或數(shù)組是否有效回官。 throw IndexOutOfBoundsException
List<String> list = new ArrayList<>();
int size = list.size();
for (int i = 0; i < size; i++) {
Preconditions.checkElementIndex(i,size);
Preconditions.checkPositionIndex(i,size);
}
}
集合
支持空元素集合 | 不支持空元素集合 |
---|---|
JDK 中的集合很多都支持空元素(ArrayList曹宴,LinkedList, HashSet, HashMap) | EnumMap,ConcurrentHashMap 和 guava中的集合大多不支持空元素 |
Enum,Tree類型支持不支持看compare方法歉提,TreeSet不支持空元素笛坦。TreeMap支持空元素。
最好嚴(yán)格控制不存null苔巨,防止出問(wèn)題
轉(zhuǎn)換成不可變集合
guava方式 比 Collections.unmodifiableXXX方法 更高效和安全;
最好使用 static final 顯示聲明版扩,更明顯
//使用of 方法直接構(gòu)建不可變集合
public static final ImmutableSet<String> COLOR_NAMES = ImmutableSet.of(
"red","orange","yellow","green","blue","purple");
//使用copyOf 轉(zhuǎn)換成不可變集合
ImmutableList<String> immutableList = ImmutableList.copyOf(Collection);
ImmutableSet immutableSet = ImmutableSet.copyOf(Collection);
ImmutableMap<Integer,Integer> immutableMap = ImmutableMap.copyOf(Map);
jdk可變集合接口 | guava中不可變版本 |
---|---|
Collection | ImmutableCollection |
List | ImmutableList |
Set | ImmutableSet |
SortedSet/NavigableSet | ImmutableSortedSet |
Map | ImmutableMap |
SortedMap | ImmutableSortedMap |
新集合類型
Multiset
可以多次添加相等的元素 統(tǒng)計(jì)出現(xiàn)的次數(shù);
Multiset<String> set = HashMultiset.create();
//Multiset<String> set = TreeMultiset.create();
//Multiset<String> set = LinkedHashMultiset.create();
//Multiset<String> set = ConcurrentHashMultiset.create();
//Multiset<String> set = ImmutableMultiset.copyOf(set);
set.add("a");
set.add("b");
set.setCount("c",101);
System.out.println(set.count("c")); //101
System.out.println(set.size()); //103
Multimap
允許key重復(fù)
//注意Multimap<K, V>不是Map<K,Collection<V>>侄泽,里面的key是有重復(fù)的资厉,但entry(key & value)不能都一樣
Multimap multimap = HashMultimap.create();
//Multimap multimap = TreeMultimap.create();
//Multimap multimap = LinkedListMultimap.create();
//ImmutableMultimap.copyOf(multimap);
multimap.put("1","2");
multimap.put("4","22");
multimap.put("13",null);
multimap.put("13","23");
multimap.put("13","23");
multimap.put("2","2");
System.out.println(multimap.get("13").size()); //2
BiMap
key和value都唯一,雙向綁定蔬顾,可以反轉(zhuǎn) key-value
BiMap<String,Integer> bitMap = HashBiMap.create();
//TreeMultimap.create();
//BiMap<DemoEnum,OtherEnum> bitMap2 = EnumBiMap.create(DemoEnum.class,OtherEnum.class);
bitMap.put("a",97);
bitMap.put("b",98);
bitMap.put("c",99);
BiMap<Integer,String> inverseMap = bitMap.inverse();
System.out.println(bitMap.get("a")); //97
System.out.println(inverseMap.get(97)); //'a'
table
用"列"和"行" 組合做key
//泛型參數(shù)分別是:列宴偿,行,值
HashBasedTable<Integer,Integer,String> table = HashBasedTable.create();
//TreeBasedTable.create();
//ImmutableTable.copyOf(table);
table.put(1,1,"1");
table.put(1,2,"2");
table.put(1,3,"3");
table.put(2,1,"4");
table.put(2,2,"5");
table.put(2,3,"6");
Map<Integer,String> map1 = table.row(2); //檢索第二列 {1=4, 2=5, 3=6}
Map<Integer,String> map2 = table.column(1); //檢索第一行 {1=1, 2=4}
String value = table.get(1,3); //3
ClassToInstanceMap
它的鍵是類型诀豁,而值是符合鍵所指類型的對(duì)象
//泛型參數(shù)代表Map支持的類型的上界
MutableClassToInstanceMap<Number> map = MutableClassToInstanceMap.create();
//ImmutableClassToInstanceMap.copyOf(map);
map.put(Integer.class,1);
map.put(Long.class,101L);
map.put(BigDecimal.class,BigDecimal.ONE);
map.put(short.class,Short.MAX_VALUE);
System.out.println(map.getInstance(short.class)); //32767
RangeSet,TreeRangeMap
不相連的窄刘、非空的區(qū)間
//使用Comparable 比較
//RangeSet會(huì)合并區(qū)間,RangeMap不會(huì)合并區(qū)間
RangeSet<Integer> rangeSet = TreeRangeSet.create();
rangeSet.add(Range.closedOpen(0,10));
rangeSet.add(Range.closed(10,20));
rangeSet.add(Range.openClosed(21,30));
System.out.println(rangeSet.toString()); //[[0..20], (21..30]
TreeRangeMap<String,String> treeRangeMap = TreeRangeMap.create();
treeRangeMap.put(Range.closed("a","f"),"a");
treeRangeMap.put(Range.closed("h","z"),"b");
treeRangeMap.remove(Range.closed("c","d"));
System.out.println(treeRangeMap.toString()); //[[a..c)=a, (d..f]=a, [h..o]=b]
字符串處理
Joiner Splitter
連接
Joiner joiner = Joiner.on(":").skipNulls(); //skipNulls()方法是直接忽略null,否者null報(bào)錯(cuò)
//Joiner.on(":").useForNull("defalut value"); useForNull(String)方法可以給定某個(gè)字符串來(lái)替換null
String str = joiner.join("A", null, "B", "C");
System.out.print(str); //A:B:C
分割
//jdk
String[] arr = ",a,,b ,".split(","); //結(jié)果:"", "a","", "b " 只有尾部的空字符串被忽略了舷胜。
//guava
//支持字符串娩践,正則,長(zhǎng)度,CharMatcher分割方式
//限制十個(gè)烹骨, 忽略空元素翻伺, 對(duì)分割后的每個(gè)元素進(jìn)行trim
Iterable<String> iterable = Splitter.on(",").limit(10).omitEmptyStrings().trimResults().split(",a,,b ,"); //結(jié)果:"a","b"
Splitter.fixedLength(3).split("aaabbbcccdd"); //按固定長(zhǎng)度拆分;最后一段可能比給定長(zhǎng)度短沮焕,但不會(huì)為空吨岭。
Splitter.onPattern("\\d").split("abc123de"); //正則分割
Joiner Splitter 類似BigDecimal都是不可變的
Joiner joiner = Joiner.on(',');
joiner.skipNulls(); // does nothing!
參考
https://github.com/google/guava
http://ifeve.com/google-guava/