溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么使用Guava中集合Collections

發(fā)布時(shí)間:2021-11-15 15:47:14 來源:億速云 閱讀:92 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要講解了“怎么使用Guava中集合Collections”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“怎么使用Guava中集合Collections”吧!

一、引子

Guava 對(duì)JDK集合的拓展,是最成熟且最受歡迎的部分。

二、Guava 集合

2.1 Immutable Collections不可變集合

1.作用

用不變的集合進(jìn)行防御性編程和性能提升。

2.簡(jiǎn)單使用
1 package guava.collect;
 2 
 3 import com.google.common.collect.ImmutableSet;
 4 
 5 /**
 6  * @author denny
 7  * @Description 不可變集合
 8  * @date 2018/7/26 下午3:16
 9  */
10 public class ImmutableCollectionsTest {
11     /**
12      * 1.直接申明靜態(tài)集合
13      */
14     public static final ImmutableSet<String> COLOR_NAMES_1 = ImmutableSet.of(
15         "red",
16         "orange",
17         "yellow",
18         "green");
19     /**
20      * 2.防御式copy
21      */
22     public static final ImmutableSet<String> COLOR_NAMES_2 = ImmutableSet.copyOf(COLOR_NAMES_1);
23 
24     /**
25      * 3.builder建造者模式
26      */
27     public static final ImmutableSet<String> COLOR_NAMES_3 = ImmutableSet.<String>builder().addAll(COLOR_NAMES_2).add("blue").build();
28 
29 
30     public static void main(String[] args) {
31         System.out.println("of:"+COLOR_NAMES_1);
32         System.out.println("防御式copy:"+COLOR_NAMES_2);
33         System.out.println("建造者模式:"+COLOR_NAMES_3);
34         System.out.println("轉(zhuǎn)換成list:"+COLOR_NAMES_3.asList());
35     }
36 }

打印:

of:[red, orange, yellow, green]
防御式copy:[red, orange, yellow, green]
建造者模式:[red, orange, yellow, green, blue]
轉(zhuǎn)換成list:[red, orange, yellow, green, blue]

2.2 新集合類型

1.作用

提供multisets, multimaps, tables, bidirectional maps等,方便各種使用場(chǎng)景。

2.簡(jiǎn)單使用

很多類,我們只舉例分析multiset、multimap接口,其它的就在測(cè)試類中體現(xiàn)。

multiset接口

繼承自JDK:java.util.Collection接口,支持多次添加相同的元素,且無序。

當(dāng)把Multiset看成普通的Collection時(shí),它表現(xiàn)得就像無序的ArrayList:

  • add(E)添加單個(gè)給定元素

  • iterator()返回一個(gè)迭代器,包含Multiset的所有元素(包括重復(fù)的元素)

  • size()返回所有元素的總個(gè)數(shù)(包括重復(fù)的元素)

當(dāng)把Multiset看作Map<E, Integer>時(shí),它也提供了符合性能期望的查詢操作:

  • count(Object)返回給定元素的計(jì)數(shù)。HashMultiset.count的復(fù)雜度為O(1),TreeMultiset.count的復(fù)雜度為O(log n)。

  • entrySet()返回Set<Multiset.Entry<E>>,和Map的entrySet類似。

  • elementSet()返回所有不重復(fù)元素的Set<E>,和Map的keySet()類似。

  • 所有Multiset實(shí)現(xiàn)的內(nèi)存消耗隨著不重復(fù)元素的個(gè)數(shù)線性增長(zhǎng)。 

multimap接口
  • 支持一個(gè)key映射多個(gè)value: k1-v1, k1-v2。

  • 提供asMap()視圖,返回Map<K, Collection<V>>,即k1->v集合(v1,v2)

各種multimap實(shí)現(xiàn)類如下:

測(cè)試類如下:

1 package guava.collect;
 2 
 3 import com.google.common.collect.BiMap;
 4 import com.google.common.collect.ClassToInstanceMap;
 5 import com.google.common.collect.HashBasedTable;
 6 import com.google.common.collect.HashBiMap;
 7 import com.google.common.collect.HashMultimap;
 8 import com.google.common.collect.HashMultiset;
 9 import com.google.common.collect.Lists;
10 import com.google.common.collect.Multimap;
11 import com.google.common.collect.Multiset;
12 import com.google.common.collect.MutableClassToInstanceMap;
13 import com.google.common.collect.Range;
14 import com.google.common.collect.RangeMap;
15 import com.google.common.collect.RangeSet;
16 import com.google.common.collect.Table;
17 import com.google.common.collect.TreeRangeMap;
18 import com.google.common.collect.TreeRangeSet;
19 
20 /**
21  * @author denny
22  * @Description 多重集合測(cè)試類
23  * @date 2018/7/26 下午6:29
24  */
25 public class MultiCollectionsTest {
26     public static void main(String[] args) {
27 
28         System.out.println("====1.Multiset=======");
29         /** 1.Multiset 專用于統(tǒng)計(jì)元素出現(xiàn)次數(shù) */
30         Multiset<String> wordsMultiset = HashMultiset.create();
31         // 添加元素
32         wordsMultiset.addAll(Lists.newArrayList("a", "b", "c", "a", "b", "a"));
33         //遍歷不同元素集合,打印次數(shù)
34         wordsMultiset.elementSet().forEach(e -> System.out.println(e + ":" + wordsMultiset.count(e)));
35 
36         System.out.println("====2.Multimap=======");
37         /** 2.Multimap 1個(gè)key多value映射 */
38         Multimap<String, Integer> multimap = HashMultimap.create();
39         multimap.put("a", 1);
40         multimap.put("b", 2);
41         multimap.put("c", 3);
42         multimap.put("a", 4);
43         System.out.println("鍵-值集合映射:");
44         // 鍵-值集合映射:asMap()轉(zhuǎn)成map(key,Collection<E>),再調(diào)用map相關(guān)方法,打印
45         multimap.asMap().entrySet().forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
46         System.out.println("鍵-單個(gè)值映射:");
47         // 鍵-單個(gè)值映射:包括重復(fù)鍵
48         multimap.entries().forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
49 
50         System.out.println("====3.BiMap=======");
51         /** 3.BiMap 鍵值反轉(zhuǎn) */
52         BiMap<String, Integer> biMap = HashBiMap.create();
53         biMap.put("a", 1);
54         biMap.put("b", 2);
55         System.out.println("鍵值對(duì)" + biMap);
56         System.out.println("鍵值反轉(zhuǎn):" + biMap.inverse());
57 
58         System.out.println("====4.Table=======");
59         /** 4.Table <R rowKey, C columnKey, V value> */
60         Table<String, String, Integer> table = HashBasedTable.create();
61         table.put("a", "b", 1);
62         table.put("a", "c", 2);
63         table.put("d", "b", 3);
64         System.out.println(table);
65         System.out.println("row a=" + table.row("a"));
66         System.out.println("column b=" + table.column("b"));
67 
68         /** 5.ClassToInstanceMap 類、實(shí)例映射 */
69         System.out.println("====5.ClassToInstanceMap=======");
70         ClassToInstanceMap<Number> classToInstanceMap = MutableClassToInstanceMap.create();
71         classToInstanceMap.putInstance(Integer.class, 1);
72         classToInstanceMap.putInstance(Double.class, 2D);
73         classToInstanceMap.putInstance(Long.class, 3L);
74         System.out.println(classToInstanceMap);
75 
76         /** 6. RangeSet 區(qū)間運(yùn)算; RangeMap 區(qū)間映射*/
77         System.out.println("====6.RangeSet、RangeMap=======");
78         RangeSet<Integer> rangeSet = TreeRangeSet.create();
79         // [1,10]
80         rangeSet.add(Range.closed(1,10));
81         // 不相連區(qū)間  [1,10] [11,15)
82         rangeSet.add(Range.closedOpen(11,15));
83         // 相連合并[11,15)+[15,20)=[11,20),最終結(jié)果:[1,10] [11,20)
84         rangeSet.add(Range.closedOpen(15,20));
85         // [1,10]-(5,10)=[1,5][10,10] ,最終結(jié)果:[1,5][10,10][11,20]
86         rangeSet.remove(Range.open(5,10));
87         System.out.println("rangeSet="+rangeSet);
88         RangeMap<Integer,String> rangeMap = TreeRangeMap.create();
89         rangeMap.put(Range.closed(1,10),"區(qū)間1");
90         // 不處理任何key的區(qū)間交集,只是簡(jiǎn)單映射
91         rangeMap.put(Range.closed(5,20),"區(qū)間2");
92         System.out.println("rangeMap="+rangeMap);
93     }
94 }

打印日志如下:

1 ====1.Multiset=======
 2 a:3
 3 b:2
 4 c:1
 5 ====2.Multimap=======
 6 鍵-值集合映射:
 7 a:[4, 1]
 8 b:[2]
 9 c:[3]
10 鍵-單個(gè)值映射:
11 a:4
12 a:1
13 b:2
14 c:3
15 ====3.BiMap=======
16 鍵值對(duì){a=1, b=2}
17 鍵值反轉(zhuǎn):{1=a, 2=b}
18 ====4.Table=======
19 {a={b=1, c=2}, d={b=3}}
20 row a={b=1, c=2}
21 column b={a=1, d=3}
22 ====5.ClassToInstanceMap=======
23 {class java.lang.Integer=1, class java.lang.Double=2.0, class java.lang.Long=3}
24 ====6.RangeSet、RangeMap=======
25 rangeSet=[[1..5], [10..10], [11..20)]
26 rangeMap=[[1..5)=區(qū)間1, [5..20]=區(qū)間2]

2.3 強(qiáng)大的集合工具類

1.作用

提供java.util.Collections中沒有的集合工具

2.簡(jiǎn)單使用

集合接口、所屬關(guān)系、Guava對(duì)應(yīng)的工具映射關(guān)系如下表:

1 package guava.collect;
 2 
 3 import com.google.common.base.Function;
 4 import com.google.common.collect.ImmutableMap;
 5 import com.google.common.collect.ImmutableSet;
 6 import com.google.common.collect.Iterables;
 7 import com.google.common.collect.Lists;
 8 import com.google.common.collect.MapDifference;
 9 import com.google.common.collect.Maps;
10 import com.google.common.collect.Sets;
11 import com.google.common.primitives.Ints;
12 
13 import java.util.List;
14 import java.util.Map;
15 import java.util.Set;
16 
17 /**
18  * @Description 
19  * @author denny
20  * @date 2018/7/27 下午2:46
21  */
22 public class UtilityClassesTest {
23 
24     public static void main(String[] args) {
25         /** 1.Iterables 迭代器工具集 */
26         System.out.println("=========Iterables=========");
27         Iterable<Integer> concate = Iterables.concat(Ints.asList(1,2,3),Ints.asList(2,3,4));
28         System.out.println("鏈接:"+concate);
29         System.out.println("元素2出現(xiàn)次數(shù):"+Iterables.frequency(concate,2));
30         System.out.println("按照指定長(zhǎng)度拆分集合:"+Iterables.partition(concate,2));
31         System.out.println("取第一個(gè)元素,為空返回默認(rèn):"+Iterables.getFirst(concate,99));
32         System.out.println("取最后元素:"+Iterables.getLast(concate));
33 
34         /** 2.Lists 列表工具集 */
35         System.out.println("=========Lists=========");
36         List list = Lists.newArrayList(1,2,3,4,5);
37         System.out.println("反轉(zhuǎn):"+Lists.reverse(list));
38         System.out.println("拆分:"+Lists.partition(list,2));
39 
40         /** 3.Sets 集合工具集 */
41         System.out.println("=========Sets=========");
42         Set<Integer> set1 = Sets.newHashSet(1,2,3);
43         Set<Integer> set2 = Sets.newHashSet(3,4,5);
44         System.out.println("并集:"+Sets.union(set1,set2));
45         System.out.println("交集:"+Sets.intersection(set1,set2));
46         System.out.println("差集(set1有set2沒有):"+Sets.difference(set1,set2));
47         System.out.println("并集-交集:"+Sets.symmetricDifference(set1,set2));
48         System.out.println("笛卡爾積:"+Sets.cartesianProduct(set1,set2));
49         System.out.println("全部子集:");
50         Sets.powerSet(set1).forEach(System.out::println);
51 
52         /** 4.Maps 集合工具集 */
53         System.out.println("=========Maps=========");
54         Map<String,Integer> map1 = Maps.newHashMap();
55         map1.put("a",1);
56         map1.put("b",2);
57         map1.put("d",5);
58         Map<String,Integer> map2 = Maps.newHashMap();
59         map2.put("a",1);
60         map2.put("b",3);
61         map2.put("c",4);
62         MapDifference<String,Integer> mapDifference = Maps.difference(map1,map2);
63         System.out.println("共有的:"+mapDifference.entriesInCommon());
64         System.out.println("key相同,value不同:"+mapDifference.entriesDiffering());
65         System.out.println("左邊獨(dú)有的:"+mapDifference.entriesOnlyOnLeft());
66         System.out.println("右邊獨(dú)有的:"+mapDifference.entriesOnlyOnRight());
67         // 字符串長(zhǎng)度
68         ImmutableSet<String> allColors = ImmutableSet.of("red", "green", "blue");
69         ImmutableMap<Integer,String> immutableMap = Maps.uniqueIndex(allColors, input -> input.length());
70         System.out.println("字符串長(zhǎng)度作為唯一key:"+immutableMap);
71     }
72 }

打印結(jié)果如下:

=========Iterables=========
鏈接:[1, 2, 3, 2, 3, 4]
元素2出現(xiàn)次數(shù):2
按照指定長(zhǎng)度拆分集合:[[1, 2], [3, 2], [3, 4]]
取第一個(gè)元素,為空返回默認(rèn):1
取最后元素:4
=========Lists=========
反轉(zhuǎn):[5, 4, 3, 2, 1]
拆分:[[1, 2], [3, 4], [5]]
=========Sets=========
并集:[1, 2, 3, 4, 5]
交集:[3]
差集(set1有set2沒有):[1, 2]
并集-交集:[1, 2, 4, 5]
笛卡爾積:[[1, 3], [1, 4], [1, 5], [2, 3], [2, 4], [2, 5], [3, 3], [3, 4], [3, 5]]
全部子集:
[]
[1]
[2]
[1, 2]
[3]
[1, 3]
[2, 3]
[1, 2, 3]
=========Maps=========
共有的:{a=1}
key相同,value不同:{b=(2, 3)}
左邊獨(dú)有的:{d=5}
右邊獨(dú)有的:{c=4}
字符串長(zhǎng)度作為唯一key{3=red, 5=green, 4=blue}

2.4 擴(kuò)展工具類

1.作用

讓實(shí)現(xiàn)和擴(kuò)展集合類變得更容易,比如創(chuàng)建Collection的裝飾器,或?qū)崿F(xiàn)迭代器

2.簡(jiǎn)單使用

不提供。guava本生就是JDK拓展,自己再去拓展,你再逗我嗎..

感謝各位的閱讀,以上就是“怎么使用Guava中集合Collections”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)怎么使用Guava中集合Collections這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI