Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the collection Collections in Guava

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use the set Collections in Guava". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use the collection Collections in Guava".

I. introduction

Guava's extension of the JDK collection is the most mature and popular part.

2. Guava set 2. 1 Immutable Collections invariant set 1. Action

Defensive programming and performance improvements with immutable collections.

two。 Simply use 1 package guava.collect; 2 3 import com.google.common.collect.ImmutableSet; 4 5 / * * 6 * @ author denny 7 * @ Description immutable collection 8 * @ date 3:16 on 2018-7-26 9 * / 10 public class ImmutableCollectionsTest {11 / * 12 * 1. Directly declare the static set 13 * / 14 public static final ImmutableSet COLOR_NAMES_1 = ImmutableSet.of (15 "red", 16 "orange", 17 "yellow", 18 "green"); 19 / * 20 * 2. Defensive copy21 * / 22 public static final ImmutableSet COLOR_NAMES_2 = ImmutableSet.copyOf (COLOR_NAMES_1); 23 24 / * 25 * 3.builder Builder Mode 26 * / 27 public static final ImmutableSet COLOR_NAMES_3 = ImmutableSet.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 ("defensive copy:" + COLOR_NAMES_2); 33 System.out.println ("Builder Mode:" + COLOR_NAMES_3); 34 System.out.println ("convert to list:" + COLOR_NAMES_3.asList ()); 35} 36}

Print:

Of: [red, orange, yellow, green] defensive copy: [red, orange, yellow, green] Builder mode: [red, orange, yellow, green, blue] converted to list: [red, orange, yellow, green, blue] 2.2 New collection type 1. Action

Provide multisets, multimaps, tables, bidirectional maps, etc., to facilitate a variety of scenarios.

two。 Easy to use

For many classes, we only give examples to analyze multiset and multimap interfaces, and the rest are reflected in the test class.

Multiset interface

Inherited from the JDK:java.util.Collection interface, the same elements can be added multiple times and out of order.

When you think of Multiset as a normal Collection, it behaves like an unordered ArrayList:

Add (E) adds a single given element

Iterator () returns an iterator that contains all the elements of Multiset (including duplicate elements)

Size () returns the total number of all elements (including duplicate elements)

When Multiset is thought of as Map, it also provides query operations that meet performance expectations:

Count (Object) returns the count of a given element. The complexity of HashMultiset.count is O (1) and that of TreeMultiset.count is O (log n).

EntrySet () returns Set, similar to the entrySet of Map.

ElementSet () returns the Set of all non-repeating elements, similar to keySet () of Map.

The memory consumption of all Multiset implementations increases linearly with the number of non-repeating elements.

Multimap interface

Support a key mapping multiple value: k1-v1, k1-v2.

Provides the asMap () view and returns Map, that is, the K1-> v collection (v1PowerV2)

Various multimap implementation classes are as follows:

The test classes are as follows:

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 denny22 * @ Description Multiset Test Class 23 * @ date 2018-7-26 afternoon 6 public class MultiCollectionsTest 2924 * / 25 public class MultiCollectionsTest {26 public static void main (String [] args) {27 28 System.out.println ("= 1.Multiset ="); 29 / * * 1.Multiset is dedicated to counting the number of occurrences of elements * / 30 Multiset wordsMultiset = HashMultiset.create () 31 / / add elements 32 wordsMultiset.addAll (Lists.newArrayList ("a", "b", "c", "a", "b", "a"); 33 / / traverse different collections of elements, 34 wordsMultiset.elementSet (). ForEach (e-> System.out.println (e + ":" + wordsMultiset.count (e); 35 36 System.out.println ("= 2.Multimap=") 37 / * * 2.Multimap 1 key multi-value mapping * / 38 Multimap 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 ("key-value set mapping:") 44 / / key-value set mapping: asMap () is converted to map (key,Collection), and then map related methods are called to print 45 multimap.asMap () .entrySet () .forEach (e-> System.out.println (e.getKey () + ":" + e.getValue (); 46 System.out.println ("key-single value mapping:") 47 / / key-single value mapping: including duplicate keys 48 multimap.entries (). ForEach (e-> System.out.println (e.getKey () + ":" + e.getValue (); 49 50 System.out.println ("= 3.BiMap="); 51 / * * 3.BiMap key value reversal * / 52 BiMap biMap = HashBiMap.create (); 53 biMap.put ("a", 1) 54 biMap.put ("b", 2); 55 System.out.println ("key-value pair" + biMap); 56 System.out.println ("key-value reversal:" + biMap.inverse ()); 57 58 System.out.println ("= 4.Table ="); 59 / * * 4.Table * / 60 Table 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 class, instance mapping * / 69 System.out.println ("= 5.ClassToInstanceMap="); 70 ClassToInstanceMap 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 interval operation RangeMap interval mapping * / 77 System.out.println ("= 6.RangeSet, RangeMap="); 78 RangeSet rangeSet = TreeRangeSet.create (); 79 / / [1Magin10] 80 rangeSet.add (Range.closed (1LJ 10)); 81 / / disconnected interval [1LJ 10] [11LJ 15) 82 rangeSet.add (Range.closedOpen (11LJ 15)) 83 / / connected merging [11pr 15) + [15jue 20) = [11pje 20), the final result: [1pje 10] [11pje 20) 84 rangeSet.add (Range.closedOpen (15jue 20)); 85 / [1pje 10]-(5jue 10) = [1pr 5] [10jue 10] [10jue 10] [11pr 20] 86 rangeSet.remove (Range.open (5jue 10); 87 System.out.println ("rangeSet=" + rangeSet) 88 RangeMap rangeMap= TreeRangeMap.create (); 89 rangeMap.put (Range.closed (1Mague 10), "interval 1"); 90 / / does not deal with any interval intersection of key, but simply maps 91 rangeMap.put (Range.closed (5Magne 20), "interval 2"); 92 System.out.println ("rangeMap=" + rangeMap); 93} 94}

Print the log as follows:

1 = 1.Multiset = 2 arow 3 3 brea 2 4 c row 1 5 = 2.Multimap = 6 key-value set mapping: 7 a: [4,1] 8 b: [2] 9 c: [3] 10 key-single value mapping: 11a row 412 av 113 banger 214 cv v 315 = reversal of key: {1a, 2i b} 18 = Multimap {a = {baud 1, cv 2}, d = {baud 3}} 20 av = {bang 1, cv 2} 21 column b = {afid 1, b 2} 21 Class java.lang.Integer=1 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] = interval 1, [5.. 20] = interval 2] 2.3 powerful set tools 1. Action

Provide collection tools that are not available in java.util.Collections

two。 Easy to use

The tool mapping relationships corresponding to collection interfaces, ownership relationships and Guava are shown in the table below:

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 denny20 * @ date 2018-7-27 2azo 4621 * / 22 public class UtilityClassesTest {23 24 public static void main (String [] args) {25 / * * 1.Iterables iterator tool set * / 26 System.out.println ("= Iterables="); 27 Iterable concate = Iterables.concat (Ints.asList (1 Mague 2), Ints.asList (2 Mague 3)) 28 System.out.println ("Link:" + concate); 29 System.out.println ("element 2 occurrences:" + Iterables.frequency (concate,2)); 30 System.out.println ("split the collection by specified length:" + Iterables.partition (concate,2)); 31 System.out.println ("take the first element and return the default if empty:" + Iterables.getFirst (concate,99)) 32 System.out.println ("fetch Last element:" + Iterables.getLast (concate)); 33 34 / * * 2.Lists list tool set * / 35 System.out.println ("= Lists="); 36 List list = Lists.newArrayList (1 System.out.println: + Lists.reverse (list)); 38 System.out.println ("split:" + Lists.partition (list,2)) 39 40 / * * 3.Sets collection toolset * / 41 System.out.println ("= Sets="); 42 Set set1 = Sets.newHashSet (1meme 2pim3); 43 Set set2 = Sets.newHashSet (3meme 4pint 5); 44 System.out.println ("Union:" + Sets.union (set1,set2)); 45 System.out.println ("intersection:" + Sets.intersection (set1,set2)) 46 System.out.println ("difference (set1 with or without set2): + Sets.difference (set1,set2)); 47 System.out.println (" Union-intersection: "+ Sets.symmetricDifference (set1,set2)); 48 System.out.println (" Cartesian Product: "+ Sets.cartesianProduct (set1,set2)); 49 System.out.println (" all subsets: "); 50 Sets.powerSet (set1) .forEach (System.out::println) 51 52 / * * 4.Maps collection toolset * / 53 System.out.println ("= Maps="); 54 Map map1 = Maps.newHashMap (); 55 map1.put ("a", 1); 56 map1.put ("b", 2); 57 map1.put ("d", 5); 58 Map map2 = Maps.newHashMap (); 59 map2.put ("a", 1) 60 map2.put ("b", 3); 61 map2.put ("c", 4); 62 MapDifference mapDifference = Maps.difference (map1,map2); 63 System.out.println ("Common:" + mapDifference.entriesInCommon ()); 64 System.out.println ("key same, value different:" + mapDifference.entriesDiffering ()); 65 System.out.println ("left unique:" + mapDifference.entriesOnlyOnLeft ()) 66 System.out.println ("unique to the right:" + mapDifference.entriesOnlyOnRight ()); 67 / / string length 68 ImmutableSet allColors = ImmutableSet.of ("red", "green", "blue"); 69 ImmutableMap immutableMap = Maps.uniqueIndex (allColors, input-> input.length ()); 70 System.out.println ("string length as unique key:" + immutableMap); 71} 72}

The print result is as follows:

= Iterables= link: [1, 2, 3, 2, 3, 4] element 2 occurrence times: 2 split the collection according to the specified length: [[1,2], [3,2], [3,4]] take the first element If empty, return default: 1 take last element: [5, 4, 3, 2, 1] split: [1, 2], [3, 4], [5] = Sets= union: [1, 2, 3, 4, 5] intersection: [3] difference (set1 has no set2): [1, 2] union-intersection: [1, 2] Cartesian product: [1, 3], [1, 4], [1, 5], [2] 3], [2, 4], [2, 5], [3, 3], [3, 4], [3, 5] all subsets: [] [1] [2] [1, 2] [3] [1, 3] [2] [1, 2] [1, 2, 3] = Maps= has the same key Value is different: {b = (2,3)} on the left: unique on the right: {3=red 4} string length as a unique key {3=red, 5=green, 4=blue} 2.4 extension tool class 1. Action

Make it easier to implement and extend collection classes, such as creating Collection decorators or implementing iterators

two。 Easy to use

Not available. Guava is the expansion of JDK. If you expand it yourself, are you kidding me again?

Thank you for reading, the above is the content of "how to use the collection Collections in Guava". After the study of this article, I believe you have a deeper understanding of how to use the collection Collections in Guava, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report