Java 开发的同学应该都使用或者听说过 Google 提供的 Guava 工具包。日常使用最多的肯定是集合相关的工具类,还有 Guava cache,除了这些之外 Guava 还提供了很多有用的功能,鉴于日常想用的时候找不到,这里就梳理一下 Guava 中那些好用的工具类,想优化代码的时候不妨过来看看!
集合
普通集合
List<String> list = Lists.newArrayList();Set<String> set = Sets.newHashSet();Map<String, String> map = Maps.newHashMap();
Set 取交集、并集、差集
HashSet<Integer> setA = Sets.newHashSet(1, 2, 3, 4, 5);HashSet<Integer> setB = Sets.newHashSet(4, 5, 6, 7, 8);Sets.SetView<Integer> union = Sets.union(setA, setB);System.out.println("union:" + union);Sets.SetView<Integer> difference = Sets.difference(setA, setB);System.out.println("difference:" + difference);Sets.SetView<Integer> intersection = Sets.intersection(setA, setB);System.out.println("intersection:" + intersection);
map 取交集、并集、差集
HashMap<String, Integer> mapA = Maps.newHashMap();mapA.put("a", 1);mapA.put("b", 2);mapA.put("c", 3);HashMap<String, Integer> mapB = Maps.newHashMap();mapB.put("b", 20);mapB.put("c", 3);mapB.put("d", 4);MapDifference<String, Integer> differenceMap = Maps.difference(mapA, mapB);Map<String, MapDifference.ValueDifference<Integer>> entriesDiffering = differenceMap.entriesDiffering();//左边差集Map<String, Integer> entriesOnlyLeft = differenceMap.entriesOnlyOnLeft();//右边差集Map<String, Integer> entriesOnlyRight = differenceMap.entriesOnlyOnRight();//交集Map<String, Integer> entriesInCommon = differenceMap.entriesInCommon();System.out.println(entriesDiffering); // {b=(2, 20)}System.out.println(entriesOnlyLeft); // {a=1}System.out.println(entriesOnlyRight); // {d=4}System.out.println(entriesInCommon); // {c=3}
不可变集合(immutable)
不可变集合的特性有:
- 在多线程操作下,是线程安全的;
- 所有不可变集合会比可变集合更有效的利用资源;
- 中途不可改变。
如果你的需求是想创建一个一经初始化后就不能再被改变的集合那么它适合你,因为这些工具类根本就没给你提供修改的 API,这意味着你连犯错误的机会都没有。
ImmutableList<Integer> iList = ImmutableList.of(12,54,87);ImmutableSet<Integer> iSet = ImmutableSet.of(354,54,764,354);ImmutableMap<String, Integer> iMap = ImmutableMap.of("k1", 453, "k2", 534);
以上 Immutable 开头的相关集合类的 add、remove 方法都被声明为 deprecated。当你手误点到了这些方法发现是 deprecated 的时候你不会还想着使用吧。
注意:每个Guava immutable集合类的实现都拒绝 null 值。
有趣的集合
MultiSet: 无序+可重复
我们映像中的 Set 应该是无序的,元素不可重复的。MultiSet 颠覆了三观,因为它可以重复。
定义一个 MultiSet 并添加元素:
Multiset<Integer> set = HashMultiset.create();set.add(3);set.add(3);set.add(4);set.add(5);set.add(4);
你还可以添加指定个数的同一个元素:
set.add(7, 3);
这表示你想添加 3 个 7。
打印出来的 MultiSet 也很有意思:
[3 x 2, 4 x 2, 5, 7 x 3]
2 个 3,2 个 4, 一个 5, 3 个 7。
获取某个元素的个数:
int count = set.count(3);
这个工具类确实很有意思,帮我们实现了 word count。
Multimap :key 可以重复的 map
这个 map 也很有意思。正常的 map 为了区分不同的 key,它倒好,直接给你来一样的 key 。
Multimap<String, String> map = LinkedHashMultimap.create();map.put("key", "haha");map.put("key", "haha1");Collection<String> key = map.get("key");System.out.println(key);
使用很简单,用一个 key 可以获取到该 key 对应的两个值,结果用 list 返回。恕我无知,我还没想到这个 map 能够使用的场景。
![](https://daimanet.oss-cn-beijing.aliyuncs.com/2021/2021-05/2021-05-10/bc6