guava中的工具集合 五
工具集合
比較和介紹
每個使用過jdk collections 的工具集合都知道java.util.Collections中的方法。guava提供了更多的工具:所有集合都可以使用靜態的方法。這些是guava中很受歡迎的部分
在jdk7之前建立集合需要重複的引數操作
List<A> list=new ArrayLIst<A>();
Guava中提供了靜態方法呼叫
List<A list=Lists.newArrayLIst();
Map<KeyType,LongishValueType> map=Maps.newLinkedHashMap();
在jdk7中鑽石方法使得方法不是那麼冗餘
LIst<A> List=new ArrayList<>();
guava使用起來更加簡單,使用工廠方法,我們可以使用初始數值去初始化物件
Set<Type> copySet=Sets.newHashSet(elements);
List<String> theseElements=Lists.newArrayList("a","b","c");
提供了可讀的引數設定方法
List<A> exactly100=Lists.newArrayListWithCapacity(100);
List<A> approx100=Lists.newArrayListWithExpectedSize(100);
這些精確的靜態工廠方法提供了很多公用的方法
Multiset<String> multiset=HashMultiset.create();
Iterables 迭代器
提供了更多的操作,連線,獲取元素,判斷等等
同時也可以支援Collection的一些方法
Fluentlterable
支援 將資料拷貝成不可變的集合
Lists類
支援在List物件上的一些操作
partition(list,int) 分開
reverse(list) list的倒序
Sets
提供一系列的集合系列操作
1.直接作為set使用,實現了set介面
2.copyInto(set)將它拷貝到另一個可變集合中
3.immutableCopy()拷貝到不可變集合中
union(Set,Set)
intersection(Set,Set)
difference(Set,Set)
symetricDifference(Set,Set)
Set<String> wordsWithPrimeLength = ImmutableSet.of("one", "two");
Set<String> primes = ImmutableSet.of("two", "three");
//兩個集合的交集
Sets.SetView<String> intersection = Sets.intersection(primes, wordsWithPrimeLength);
intersection.immutableCopy();
其他Set方法
public void test01() {
Set<String> wordsWithPrimeLength = ImmutableSet.of("one", "two");
Set<String> primes = ImmutableSet.of("two", "three");
//兩個集合的交集
Sets.SetView<String> intersection = Sets.intersection(primes, wordsWithPrimeLength);
intersection.immutableCopy();
}
public void test02() {
Set<String> animals = ImmutableSet.of("gerbil", "hamster");
Set<String> fruits = ImmutableSet.of("apple", "orange", "banana");
Set<List<String>> product = Sets.cartesianProduct(animals, fruits);
// {{"gerbil", "apple"}, {"gerbil", "orange"}, {"gerbil", "banana"},
// {"hamster", "apple"}, {"hamster", "orange"}, {"hamster", "banana"}}
Set<Set<String>> animalSets = Sets.powerSet(animals);
// {{}, {"gerbil"}, {"hamster"}, {"gerbil", "hamster"}}
}
靜態工廠方法
HashSet
LinkedHashSet
TreeSet
Maps
uniqueIndex(Iterable,Function) 我們有一系列的字串,我們想要獲取特定長度的字串
Maps.difference(Map,Map) 允許比較兩個mao中的不同,返回MapDifference物件
eg
BiMap中的方法
BiMap中同樣也可以使用Map中的方法
Multisets中的方法
Multisets.copyHighestCountFirst();
Multimaps
Multimaps.index(Iterable,Function)
找一些有共同特性的屬性
Multimaps.invertFrom(Multimap toInvert,Multimap dest)反轉一個類中的值和健
Multimaps.forMap
特別有用的一個方法
forMap 將map當作一個SetMultimap
例如
Wrappers
提供了傳統的wrapper 方法獲取傳統的multimap基於map和collection.
public void test09(){
ListMultimap<String,Integer> myMultimap=Multimaps.newListMultimap(
Maps.<String, Collection<Integer>>newTreeMap(), new Supplier<List<Integer>>() {
public List<Integer> get() {
return Lists.newLinkedList();
}
}
);
}
Tables的公用方法
customTable
可以建立指定任何行列的map
Tables.transpose方法可以將Table<R,C,V> 行列反轉
Table<C,R,V>
擴充套件的集合工具類
有時候要寫自己的擴充套件集合類,guava使得這種擴充套件更簡單
Forwarding
裝飾物件方法進行擴充套件
PeekingIterator
包裝方法Iterator 返回 PeekingIterator