Guava——CollectionUtils

java.util.Collections強大的工具包摊趾。

Util 與Collection的對應(yīng)關(guān)系

Interface JDK or Guava? Corresponding Guava utility class
Collection JDK Collections2
List JDK Lists
Set JDK Sets
SortedSet JDK Sets
Map JDK Maps
SortedMap JDK Maps
Queue JDK Queues
Multiset Guava Multisets
Multimap Guava Multimaps
BiMap Guava Maps
Table Guava Tables

Looking for transform, filter, and the like? That stuff is in our functional programming article, under functional idioms.

Iterable

Whenever possible, Guava prefers to provide utilities accepting an Iterable rather than a Collection. Here at Google, it's not out of the ordinary to encounter a "collection" that isn't actually stored in main memory, but is being gathered from a database, or from another data center, and can't support operations like size() without actually grabbing all of the elements.

As a result, many of the operations you might expect to see supported for all collections can be found in Iterables. Additionally, most Iterables methods have a corresponding version in Iterators that accepts the raw iterator.

The overwhelming majority of operations in the Iterables class are lazy: they only advance the backing iteration when absolutely necessary. Methods that themselves return Iterables return lazily computed views, rather than explicitly constructing a collection in memory.

As of Guava 12, Iterables is supplemented by the FluentIterable class, which wraps an Iterable and provides a "fluent" syntax for many of these operations.

Method Description See Also
concat(Iterable<Iterable>) Returns a lazy view of the concatenation of several iterables. concat(Iterable...)
frequency(Iterable, Object) Returns the number of occurrences of the object. Compare Collections.frequency(Collection, Object); see Multiset
partition(Iterable, int) Returns an unmodifiable view of the iterable partitioned into chunks of the specified size. Lists.partition(List, int), paddedPartition(Iterable, int)
getFirst(Iterable, T default) Returns the first element of the iterable, or the default value if empty. Compare Iterable.iterator().next(), FluentIterable.first()
getLast(Iterable) Returns the last element of the iterable, or fails fast with a NoSuchElementExceptionif it's empty. getLast(Iterable, T default), FluentIterable.last()
elementsEqual(Iterable, Iterable) Returns true if the iterables have the same elements in the same order. Compare List.equals(Object)
unmodifiableIterable(Iterable) Returns an unmodifiable view of the iterable. Compare Collections.unmodifiableCollection(Collection)
limit(Iterable, int) Returns an Iterablereturning at most the specified number of elements. FluentIterable.limit(int)
getOnlyElement(Iterable) Returns the only element in Iterable. Fails fast if the iterable is empty or has multiple elements. getOnlyElement(Iterable, T default)

Collection-Like

Typically, collections support these operations naturally on other collections, but not on iterables.

Method Analogous Collection method FluentIterable equivalent
addAll(Collection addTo, Iterable toAdd) Collection.addAll(Collection)
contains(Iterable, Object) Collection.contains(Object) FluentIterable.contains(Object)
removeAll(Iterable removeFrom, Collection toRemove) Collection.removeAll(Collection)
retainAll(Iterable removeFrom, Collection toRetain) Collection.retainAll(Collection)
size(Iterable) Collection.size() FluentIterable.size()
toArray(Iterable, Class) Collection.toArray(T[]) FluentIterable.toArray(Class)
isEmpty(Iterable) Collection.isEmpty() FluentIterable.isEmpty()
get(Iterable, int) List.get(int) FluentIterable.get(int)
toString(Iterable) Collection.toString() FluentIterable.toString()

Each of these operations delegates to the corresponding Collection interface method when the input is actually a Collection. For example, if Iterables.size is passed a Collection, it will call the Collection.size method instead of walking through the iterator.

Method Analogous Collection method FluentIterable equivalent
addAll(Collection addTo, Iterable toAdd) Collection.addAll(Collection)
contains(Iterable, Object) Collection.contains(Object) FluentIterable.contains(Object)
removeAll(Iterable removeFrom, Collection toRemove) Collection.removeAll(Collection)
retainAll(Iterable removeFrom, Collection toRetain) Collection.retainAll(Collection)
size(Iterable) Collection.size() FluentIterable.size()
toArray(Iterable, Class) Collection.toArray(T[]) FluentIterable.toArray(Class)
isEmpty(Iterable) Collection.isEmpty() FluentIterable.isEmpty()
get(Iterable, int) List.get(int) FluentIterable.get(int)
toString(Iterable) Collection.toString() FluentIterable.toString()

Lists

Method Description
partition(List, int) Returns a view of the underlying list, partitioned into chunks of the specified size.
reverse(List) Returns a reversed view of the specified list. Note: if the list is immutable, consider ImmutableList.reverse() instead.

Sets

These return a SetView, which can be used:

  • as a Set directly, since it implements the Set interface
  • by copying it into another mutable collection with copyInto(Set)
  • by making an immutable copy with immutableCopy()
Method
union(Set, Set)
intersection(Set, Set)
difference(Set, Set)
symmetricDifference(Set, Set)

Maps

uniqueIndex

Maps.uniqueIndex(Iterable, Function) addresses the common case of having a bunch of objects that each have some unique attribute, and wanting to be able to look up those objects based on that attribute.

Let's say we have a bunch of strings that we know have unique lengths, and we want to be able to look up the string with some particular length.

ImmutableMap<Integer, String> stringsByIndex = Maps.uniqueIndex(strings, new Function<String, Integer> () {
    public Integer apply(String string) {
      return string.length();
    }
  });

difference

Maps.difference(Map, Map) allows you to compare all the differences between two maps. It returns a MapDifference object, which breaks down the Venn diagram into:

Method Description
entriesInCommon() The entries which are in both maps, with both matching keys and values.
entriesDiffering() The entries with the same keys, but differing values. The values in this map are of type MapDifference.ValueDifference, which lets you look at the left and right values.
entriesOnlyOnLeft() Returns the entries whose keys are in the left but not in the right map.
entriesOnlyOnRight() Returns the entries whose keys are in the right but not in the left map.
Map<String, Integer> left = ImmutableMap.of("a", 1, "b", 2, "c", 3);
Map<String, Integer> right = ImmutableMap.of("b", 2, "c", 4, "d", 5);
MapDifference<String, Integer> diff = Maps.difference(left, right);

diff.entriesInCommon(); // {"b" => 2}
diff.entriesDiffering(); // {"c" => (3, 4)}
diff.entriesOnlyOnLeft(); // {"a" => 1}
diff.entriesOnlyOnRight(); // {"d" => 5}

BiMap utilities

The Guava utilities on BiMap live in the Maps class, since a BiMap is also a Map.

BiMap utility Corresponding Map utility
synchronizedBiMap(BiMap) Collections.synchronizedMap(Map)
unmodifiableBiMap(BiMap) Collections.unmodifiableMap(Map)

Multisets

Multimaps

index

構(gòu)建另外的索引,可以分組
Let's say we want to group strings based on their length.

ImmutableSet<String> digits = ImmutableSet.of(
    "zero", "one", "two", "three", "four",
    "five", "six", "seven", "eight", "nine");
Function<String, Integer> lengthFunction = new Function<String, Integer>() {
  public Integer apply(String string) {
    return string.length();
  }
};
ImmutableListMultimap<Integer, String> digitsByLength = Multimaps.index(digits, lengthFunction);
/*
 * digitsByLength maps:
 *  3 => {"one", "two", "six"}
 *  4 => {"zero", "four", "five", "nine"}
 *  5 => {"three", "seven", "eight"}
 */

invertFrom

因為multiMap可構(gòu)建N:N關(guān)系的key:value嘀略,所以可以invert一下

Since Multimap can map many keys to one value, and one key to many values, it can be useful to invert a Multimap. Guava provides invertFrom(Multimap toInvert, Multimap dest) to let you do this, without choosing an implementation for you.

NOTE: If you are using an ImmutableMultimap, consider ImmutableMultimap.inverse()instead.

ArrayListMultimap<String, Integer> multimap = ArrayListMultimap.create();
multimap.putAll("b", Ints.asList(2, 4, 6));
multimap.putAll("a", Ints.asList(4, 2, 1));
multimap.putAll("c", Ints.asList(2, 5, 3));

TreeMultimap<Integer, String> inverse = Multimaps.invertFrom(multimap, TreeMultimap.<String, Integer> create());
// note that we choose the implementation, so if we use a TreeMultimap, we get results in order
/*
 * inverse maps:
 *  1 => {"a"}
 *  2 => {"a", "b", "c"}
 *  3 => {"c"}
 *  4 => {"a", "b"}
 *  5 => {"c"}
 *  6 => {"b"}
 */

forMap

Need to use a Multimap method on a Map? forMap(Map) views a Map as a SetMultimap. This is particularly useful, for example, in combination with Multimaps.invertFrom.

Map<String, Integer> map = ImmutableMap.of("a", 1, "b", 1, "c", 2);
SetMultimap<String, Integer> multimap = Multimaps.forMap(map);
// multimap maps ["a" => {1}, "b" => {1}, "c" => {2}]
Multimap<Integer, String> inverse = Multimaps.invertFrom(multimap, HashMultimap.<Integer, String> create());
// inverse maps [1 => {"a", "b"}, 2 => {"c"}]

Wrappers

Multimap type Unmodifiable Synchronized Custom
Multimap unmodifiableMultimap synchronizedMultimap newMultimap
ListMultimap unmodifiableListMultimap synchronizedListMultimap newListMultimap
SetMultimap unmodifiableSetMultimap synchronizedSetMultimap newSetMultimap
SortedSetMultimap unmodifiableSortedSetMultimap synchronizedSortedSetMultimap newSortedSetMultimap

Multimaps provides the traditional wrapper methods, as well as tools to get custom Multimap implementations based on Map and Collection implementations of your choice.

Multimap type Unmodifiable Synchronized Custom
Multimap unmodifiableMultimap synchronizedMultimap newMultimap
ListMultimap unmodifiableListMultimap synchronizedListMultimap newListMultimap
SetMultimap unmodifiableSetMultimap synchronizedSetMultimap newSetMultimap
SortedSetMultimap unmodifiableSortedSetMultimap synchronizedSortedSetMultimap newSortedSetMultimap

Note that the custom Multimap methods expect a Supplier argument to generate fresh new collections. Here is an example of writing a ListMultimap backed by a TreeMap mapping to LinkedList.

ListMultimap<String, Integer> myMultimap = Multimaps.newListMultimap(
  Maps.<String, Collection<Integer>>newTreeMap(),
  new Supplier<LinkedList<Integer>>() {
    public LinkedList<Integer> get() {
      return Lists.newLinkedList();
    }
  });

Tables

customTable

Comparable to the Multimaps.newXXXMultimap(Map, Supplier) utilities,Tables.newCustomTable(Map, Supplier<Map>) allows you to specify a Table implementation using whatever row or column map you like.

// use LinkedHashMaps instead of HashMaps
Table<String, Character, Integer> table = Tables.newCustomTable(
  Maps.<String, Map<Character, Integer>>newLinkedHashMap(),
  new Supplier<Map<Character, Integer>> () {
    public Map<Character, Integer> get() {
      return Maps.newLinkedHashMap();
    }
  });
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末缩滨,一起剝皮案震驚了整個濱河市呐萨,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌底哥,老刑警劉巖咙鞍,帶你破解...
    沈念sama閱讀 222,590評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異趾徽,居然都是意外死亡续滋,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評論 3 399
  • 文/潘曉璐 我一進(jìn)店門孵奶,熙熙樓的掌柜王于貴愁眉苦臉地迎上來疲酌,“玉大人,你說我怎么就攤上這事了袁±士遥” “怎么了?”我有些...
    開封第一講書人閱讀 169,301評論 0 362
  • 文/不壞的土叔 我叫張陵载绿,是天一觀的道長粥诫。 經(jīng)常有香客問我,道長崭庸,這世上最難降的妖魔是什么怀浆? 我笑而不...
    開封第一講書人閱讀 60,078評論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮怕享,結(jié)果婚禮上执赡,老公的妹妹穿的比我還像新娘。我一直安慰自己熬粗,他們只是感情好搀玖,可當(dāng)我...
    茶點故事閱讀 69,082評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著驻呐,像睡著了一般灌诅。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上含末,一...
    開封第一講書人閱讀 52,682評論 1 312
  • 那天猜拾,我揣著相機與錄音,去河邊找鬼佣盒。 笑死挎袜,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播盯仪,決...
    沈念sama閱讀 41,155評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼紊搪,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了全景?” 一聲冷哼從身側(cè)響起耀石,我...
    開封第一講書人閱讀 40,098評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎爸黄,沒想到半個月后滞伟,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,638評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡炕贵,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,701評論 3 342
  • 正文 我和宋清朗相戀三年梆奈,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片称开。...
    茶點故事閱讀 40,852評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡亩钟,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出钥弯,到底是詐尸還是另有隱情径荔,我是刑警寧澤督禽,帶...
    沈念sama閱讀 36,520評論 5 351
  • 正文 年R本政府宣布脆霎,位于F島的核電站,受9級特大地震影響狈惫,放射性物質(zhì)發(fā)生泄漏睛蛛。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,181評論 3 335
  • 文/蒙蒙 一胧谈、第九天 我趴在偏房一處隱蔽的房頂上張望忆肾。 院中可真熱鬧,春花似錦菱肖、人聲如沸客冈。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽场仲。三九已至,卻和暖如春退疫,著一層夾襖步出監(jiān)牢的瞬間渠缕,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評論 1 274
  • 我被黑心中介騙來泰國打工褒繁, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留亦鳞,地道東北人。 一個月前我還...
    沈念sama閱讀 49,279評論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像燕差,于是被迫代替她去往敵國和親遭笋。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,851評論 2 361

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,347評論 0 10
  • 前天有個小伙伴在分答上問我吵血,對于大學(xué)生知識付費平臺的看法;恰好我昨晚接受在行上的一個約見時偷溺,又被問到了這個話題蹋辅,今...
    孫凌聊校園閱讀 380評論 0 20
  • 寫一篇回憶,贈給我的老友挫掏。 我們已許久沒有聯(lián)系侦另。久到似乎已記不起那些點滴,如果沒有我們相互之間的提醒尉共。 現(xiàn)在的我已...
    亂筆閱讀 356評論 2 0
  • 一個人走在城市的黃昏袄友,孤獨被斜陽曳成獵獵的旗殿托,招搖在四周的暮云里。走在行色匆匆的人流中剧蚣,忽然發(fā)現(xiàn)自己失去了方向支竹。在...
    枔惘閱讀 293評論 13 7
  • ??【晨間計劃 | 朝夕打卡】 ??【晨間計劃 | 喜馬拉雅?得到音頻】 ??【晨間計劃 | 晨間日記?復(fù)盤?運動...
    差不多小姐少女薇閱讀 142評論 0 0