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 Java core tool library Guava

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article editor for you a detailed introduction of the "Java core tool library Guava how to use", the content is detailed, the steps are clear, the details are handled properly, I hope that this "Java core tool library Guava how to use" article can help you solve doubts, the following follow the editor's ideas slowly in-depth, together to learn new knowledge.

Set ordinary set List list = Lists.newArrayList (); Set set = Sets.newHashSet (); Map map = Maps.newHashMap (); Set takes intersection, union, difference HashSet setA = Sets.newHashSet (1,2,3,4,5); HashSet setB = Sets.newHashSet (4,5,6,7,8); Sets.SetView union = Sets.union (setA, setB); System.out.println ("union:" + union); Sets.SetView difference = Sets.difference (setA, setB) System.out.println ("difference:" + difference); Sets.SetView intersection = Sets.intersection (setA, setB); System.out.println ("intersection:" + intersection); map take intersection, union, difference HashMap mapA = Maps.newHashMap (); mapA.put ("a", 1); mapA.put ("b", 2); mapA.put ("c", 3); HashMap mapB = Maps.newHashMap (); mapB.put ("b", 20); mapB.put ("c", 3) MapB.put ("d", 4); MapDifference differenceMap = Maps.difference (mapA, mapB); Map entriesDiffering = differenceMap.entriesDiffering (); / / left difference Map entriesOnlyLeft = differenceMap.entriesOnlyOnLeft (); / / right difference Map entriesOnlyRight = differenceMap.entriesOnlyOnRight (); / / intersection Map entriesInCommon = differenceMap.entriesInCommon (); System.out.println (entriesDiffering); / / {b = (2,20)} System.out.println (entriesOnlyLeft); / / {axi1} System.out.println (entriesOnlyRight) / / {dong4} System.out.println (entriesInCommon); / / {canti3} immutable set (immutable)

The properties of immutable sets are:

Under multithreaded operation, it is thread safe.

All immutable sets use resources more efficiently than variable sets.

You can't change it halfway.

If your requirement is to create a collection that cannot be changed once initialized, then it suits you, because these utility classes don't give you a modified API at all, which means you don't even have a chance to make a mistake.

ImmutableList iList = ImmutableList.of (12454 ImmutableList iList 87); ImmutableSet iSet = ImmutableSet.of (354 54764354); ImmutableMap iMap = ImmutableMap.of ("K1", 453,534)

The add and remove methods of the related collection classes at the beginning of the above Immutable are declared as deprecated. When you miss these methods and find out it's deprecated, you don't still want to use it.

Note: the implementation of each Guava immutable collection class rejects the null value.

Interesting collection

MultiSet: disorder + repeatability

The Set in our image should be unordered and the elements should not be repeatable. MultiSet subverts the three values because it can be repeated.

Define a MultiSet and add elements:

Multiset set = HashMultiset.create (); set.add (3); set.add (3); set.add (4); set.add (5); set.add (4)

You can also add the same element with a specified number:

Set.add (7,3)

This means that you want to add three 7s.

The printed MultiSet is also interesting:

[3 x 2, 4 x 2, 5, 7 x 3]

Two 3pens, two 4s, one 5pals and three 7s.

Get the number of elements:

Int count = set.count (3)

This utility class is really interesting and helps us implement word count.

Multimap: map that key can repeat

This map is also very interesting. Normal map in order to distinguish between different key, it is better, directly give you the same key.

Multimap map = LinkedHashMultimap.create (); map.put ("key", ""); map.put ("key", "1"); Collection key = map.get ("key"); System.out.println (key)

It is easy to use, you can get two values corresponding to the key with a key, and the results are returned with list. Excuse my ignorance, but I haven't thought of this scenario where map can be used.

Multimap provides several implementations:

Multimap implements key field type value field type ArrayListMultimapHashMapArrayListHashMultimapHashMapHashSetLinkedListMultimapLinkedHashMapLinkedListLinkedHashMultimapLinkedHashMapLinkedHashSetTreeMultimapTreeMapTreeSetImmutableListMultimapImmutableMapImmutableListImmutableSetMultimapImmutableMapImmutableSet bidirectional Map

(Bidirectional Map) Keys and values cannot be duplicated

This is a little more normal. If the key is repeated, the key will be overwritten, and if the value is duplicated, an error will be reported.

Public static void main (String [] args) {BiMap biMap = HashBiMap.create (); biMap.put ("key", ""); biMap.put ("key", "1"); biMap.put ("key1", ""); String value = biMap.get ("key"); System.out.println (value);}

In the above example, there are two keys "key". When you run, you can find that get will overwrite "" with "1", and there are also two value with "". You will find that running the above code will not report an error, because the corresponding value of "key" has been overwritten by "1". Otherwise, it will be wrong.

Double-key map-Super practical

Double-key map, I suddenly feel that I have discovered a new world. For example, I have a business scenario where people in the company are distinguished by position and department. Key can use position + department to form a string, so we don't have this kind of trouble after we have double key map.

Public static void main (String [] args) {Table tables = HashBasedTable.create (); tables.put ("Finance Department", "Director", Lists.newArrayList ()); tables.put ("Finance Department", "staff", Lists.newArrayList ()); tables.put ("legal Department", "Assistant", Lists.newArrayList ()); System.out.println (tables);} tools

What we are familiar with in JDK is Collections, a collection tool class, which provides some basic set processing conversion functions, but in practice, many requirements are not simply sorting, or comparing numerical values, and then Guava has done a lot of improvements and optimizations on this basis, which can be said to be one of the most mature / popular modules of Guava.

Array correlation: Lists

Collection dependence: Sets

Map related: Maps

Connector (Joiner) and delimiter (Splitter)

The use of Joiner as a connector is very simple. The following example is to convert list to a string connected with a connector:

List list = Lists.newArrayList (); list.add (34); list.add (64); list.add (267); list.add (865); String result = Joiner.skipNulls (). On ("-") .join (list); System.out.println (result); output: 34-64-267865

Convert map to a string connected by a custom connector:

Map map = Maps.newHashMap (); map.put ("key1", 45); map.put ("key2", 234); String result = Joiner.on (",") .withKeyValueSeparator ("=") .join (map); System.out.println (result); output: key1=45,key2=234

The use of the delimiter Splitter is also simple:

String str = "1-2-3-4-5-6"; List list = Splitter.on ("-") .splitToList (str); System.out.println (list); output: [1,2,3,4,5,6]

If there are spaces in the string, you can also remove the spaces first:

String str = "1-2-3-4-5-6"; List list = Splitter.on ("-"). OmitEmptyStrings (). TrimResults (). SplitToList (str); System.out.println (list)

Convert String to map:

String str = "key1=54,key2=28"; Map map = Splitter.on (","). WithKeyValueSeparator ("=") .split (str); System.out.println (map); output: implementation of {key1=54,key2=28} Comparator

Java provides Comparator that you can use to sort objects. Guava provides a sorter Ordering class that encapsulates a lot of practical operations.

Ordering provides some useful methods:

Natural () sorts sortable types naturally, such as numbers by size and dates by order.

UsingToString () makes a dictionary sort by the string form of the object [lexicographical ordering]

From (Comparator) converts a given Comparator into a sequencer

Reverse () gets the sorter with opposite semantics

NullsFirst () uses the current sequencer, but puts the null value first in addition.

NullsLast () uses the current sequencer, but puts the null value at the bottom in addition.

Compound (Comparator) synthesizes another comparator to handle equality in the current sequencer. Lexicographical () returns the collator of the iterable object Iterable of that type based on the sequencer of the processing type T.

OnResultOf (Function) calls Function on the elements in the collection and sorts them with the current sorter by the returned value.

Example:

UserInfo build = UserInfo.builder (). Uid (234L). Gender (1). Build (); UserInfo build1 = UserInfo.builder (). Uid (4354L). Gender (0). Build (); Ordering byOrdering = Ordering.natural (). NullsFirst (). OnResultOf ((Function) input-> input.getGender ()); System.out.println (byOrdering.compare (build1, build))

The gender of build is greater than that of build1, so return-1 and vice versa.

Count the running time of intermediate code

The Stopwatch class provides time statistics, which is equivalent to encapsulating the logic of calling System.currentTimeMillis ().

Stopwatch stopwatch = Stopwatch.createStarted (); try {/ / TODO Analog Business Logic Thread.sleep (2000L);} catch (InterruptedException e) {e.printStackTrace ();} long nanos = stopwatch.elapsed (TimeUnit.SECONDS); System.out.println (nanos); Guava Cache-Local Cache component

Guava Cache is so frequently used in daily use that it doesn't even realize that it's a third-party utility class but treats it as an implementation that comes with JDK.

/ / LoadingCache is the cache implementation of Cache LoadingCache cache = CacheBuilder.newBuilder () / / sets the cache size. MaximumSize (1000) / / sets the expiration time. RefreshAfterWrite (2) refreshAfterWrite (2) TimeUnit.MINUTES) / / enable the statistics function of the cache .recordStats () / / build the cache. Build (new CacheLoader () {/ / implement here how to get @ Override public Object load (String s) throws Exception {return new Object () if you can't find value according to key. } / / override this method @ Override public Map loadAll (Iterable) if the batch load contains a method that is better than repeatedly calling load

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

Development

Wechat

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

12
Report