Guava——CollectionUtils

java.util.Collections强大的工具包。

Util 与Collection的对应关系

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

构建另外的索引,可以分组
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可构建N: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();
    }
  });
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,723评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,080评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,604评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,440评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,431评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,499评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,893评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,541评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,751评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,547评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,619评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,320评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,890评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,896评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,137评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,796评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,335评论 2 342

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,279评论 0 10
  • 前天有个小伙伴在分答上问我,对于大学生知识付费平台的看法;恰好我昨晚接受在行上的一个约见时,又被问到了这个话题,今...
    孙凌聊校园阅读 370评论 0 20
  • 写一篇回忆,赠给我的老友。 我们已许久没有联系。久到似乎已记不起那些点滴,如果没有我们相互之间的提醒。 现在的我已...
    乱笔阅读 351评论 2 0
  • 一个人走在城市的黄昏,孤独被斜阳曳成猎猎的旗,招摇在四周的暮云里。走在行色匆匆的人流中,忽然发现自己失去了方向。在...
    枔惘阅读 290评论 13 7
  • ❤️【晨间计划 | 朝夕打卡】 ❤️【晨间计划 | 喜马拉雅➕得到音频】 ❤️【晨间计划 | 晨间日记➕复盘➕运动...
    差不多小姐少女薇阅读 128评论 0 0