当前位置:网站首页>Don't build the wheel again. It is recommended to use Google guava open source tool class library. It is really powerful!
Don't build the wheel again. It is recommended to use Google guava open source tool class library. It is really powerful!
2022-06-29 13:33:00 【Java technology stack】
Google Guava summary
1、Guava It's a group from Google At the heart of Java library , Include new set types ( Such as multimap and multiset)、 Immutable set 、 Graphics library and for concurrency 、I/O、 hash 、 cache 、 The original language 、 String and so on ! Widely used in Google Most of Java In the project , It's also widely used by many other companies .
2、guava github Open source address :GitHub - google/guava:
3、 Official website user manual
4、com.google.guava rely on :
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>29.0-jre</version>
</dependency>Immutable sets and objects
1、 Making immutable copies of objects is a good defensive programming technique , Immutable objects have many advantages , Include :
- Safe for untrusted Libraries .
- Thread safety : Can be used by multiple threads , No contention risk .
- There is no need to support mutation , And it can save time and space , All immutable collection implementations save more memory than their mutable siblings .
- Can be used as a constant , And expect it to remain the same .
2、 The main points of : Every Guava Immutable set implementations reject null value .Guava It is recommended to use null value , Most of the time , encounter null The value will throw an exception .
3、 An immutable ImmutableXxx Collections can be created in several ways :
- Use copyOf Method , Such as
ImmutableSet.copyOf(set) - Use of Method , Such as
ImmutableSet.of("a", "b", "c")orImmutableMap.of("a", 1, "b", 2) - Use Builder Method ,.
4、Guava by java jdk Each standard collection type provides an easy-to-use, immutable version , Include Guava Own set variants , by java The immutable versions provided are inherited java jdk From the interface of , So the operation is basically the same . The implementation classes of the following interfaces also have corresponding immutable versions .
| Interface | JDK perhaps Guava | Immutable version |
|---|---|---|
| Collection | JDK | ImmutableCollection |
| List | JDK | ImmutableList |
| Set | JDK | ImmutableSet |
| SortedSet/NavigableSet | JDK | ImmutableSortedSet |
| Map | JDK | ImmutableMap |
| SortedMap | JDK | ImmutableSortedMap |
| Multiset | Guava | ImmutableMultiset |
| SortedMultiset | Guava | ImmutableSortedMultiset |
| Multimap | Guava | ImmutableMultimap |
| ListMultimap | Guava | ImmutableListMultimap |
| SetMultimap | Guava | ImmutableSetMultimap |
| BiMap | Guava | ImmutableBiMap |
| ClassToInstanceMap | Guava | ImmutableClassToInstanceMap |
| Table | Guava | ImmutableTable |
Online demo source code :
https://github.com/main/java/com/wmx/guava/ImmutableCollectionTest.java
Official document
https://github.com/google/guava/wiki/ImmutableCollectionsExplained
Recommend a Spring Boot Basic tutorials and practical examples :
Guava New collection type
1、Guava Many new collection types have been introduced , These types are not in Java JDK in , But it's very useful , These are all for the sake of JDK The collection framework is designed to coexist happily , Instead of stuffing things into JDK In set abstraction .
Multiset Repeatable set
1、Guava Provides a new collection type Multiset, It supports adding multiple identical elements , Members can appear more than once .
2、Multiset amount to Set, The difference lies in Multiset You can add the same elements , It uses a HashMap To maintain the ,
3、Multiset It also has its own implementation class , Commonly used HashMultiset、LinkedHashMultiset、TreeMultiset etc. ,HashMultiset 、TreeMultiset Is chaotic ,LinkedHashMultiset Is ordered , The operation is exactly the same JDK Of HashSet、TreeSet、LinkedHashSet.
Online demo source code
Multimap Multiple mapping
1、 Every experienced Java Programmers have implemented... Somewhere Map<K、List<V>> or Map<K、Set<V>>,Guava Of Multimap The framework makes it easy to handle mapping from keys to multiple values , Multiple mapping is a general method of associating keys with any number of values .
2、 conceptually , There are two ways to think of multiple mappings as a collection of mappings from a single key to a single value :

3、Multimap A variety of implementations are provided :
| Multimap | Realization key It uses | value It uses |
|---|---|---|
| ArrayListMultimap | HashMap | ArrayList |
| HashMultimap | HashMap | HashSet |
| LinkedListMultimap * | LinkedHashMap* | LinkedList* |
| LinkedHashMultimap** | LinkedHashMap | LinkedHashSet |
| TreeMultimap | TreeMap | TreeSet |
| ImmutableListMultimap | ImmutableMap | ImmutableList |
| ImmutableSetMultimap | ImmutableMap | ImmutableSet |
4、 In addition to the immutable implementation , Each implementation supports null keys and values . Not all implementations are implemented as Map<K,Collection<V>> Realized ( Especially some Multimap The implementation uses a custom hash table to minimize overhead .)
Online demo source code
Recommend a Spring Boot Basic tutorials and practical examples :
BiMap Bidirectional mapping
1、 The traditional way to map values back to keys is to maintain two separate mappings , And keep them synchronized , But it's easy to make mistakes , And when a value already exists in the mapping
Map<String, Integer> nameToId = Maps.newHashMap();
Map<Integer, String> idToName = Maps.newHashMap();
nameToId.put("Bob", 42);
idToName.put(42, "Bob");2、BiMap A variety of implementations are provided :
| Key value mapping implementation | Value key mapping implementation | Corresponding BiMap |
|---|---|---|
| HashMap | HashMap | HashBiMap |
| ImmutableMap | ImmutableMap | ImmutableBiMap |
| EnumMap | EnumMap | EnumBiMap |
| EnumMap | HashMap | EnumHashBiMap |
Online demo source code :
https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/guava/BiMapTest.java
Table Table structure data
1、 When trying to index multiple keys at once , You will get something like Map<FirstName,Map<LastName,Person>> Code for , It's ugly , And it's embarrassing to use .Guava Provides a new collection type Table, It supports any “row” The type and “column” This use case of type .
2、Table A variety of implementations are provided :
- HashBasedTable: It's basically from
HashMap<R,HashMap<C,V>>Supported by . - TreeBasedTable: It's basically from
TreeMap<R,TreeMap<C,V>>Supported by . - ImmutableTable
- ArrayTable: It is required to specify the full range of rows and columns during construction , Memory intensive and two-dimensional arrays are supported to improve efficiency ,ArrayTable Works a little differently from other implementations
Online demo source code :
https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/guava/TableTest.java
ClassToInstanceMap Type mapping to instance
1、 Sometimes key Not a single type , But many types ,Guava This provides ClassToInstanceMap,key It can be of many types ,value Is an instance of this type .
2、ClassToInstanceMap The realization of : MutableClassToInstanceMap and ImmutableClassToInstanceMap The implementation of the .
Online demo source code :
https://github.com/wangmaoxiong/src/main/java/com/wmx/guava/ClassToInstanceMapTest.java
JDK Collection helper class
1、 Any JDK Programmers with experience in the collection framework know and like the utilities provided java.util.Collections,Guava There are many static method utilities available for collections .
| Interface | Belong to JDK still Guava | Corresponding Guava API |
|---|---|---|
| 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 |
Lists The online demo :
https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/guava/ListsTest.java
Sets The online demo :
https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/guava/SetsTest.java
JDK Basic type helper class
1、Guava by Java JDK The basic type of provides utility classes :
| Basic types | Guava Auxiliary tools |
|---|---|
| byte | Bytes, SignedBytes, UnsignedBytes |
| short | Shorts |
| int | Ints, UnsignedInteger, UnsignedInts |
| long | Longs, UnsignedLong, UnsignedLongs |
| float | Floats |
| double | Doubles |
| char | Chars |
| boolean | Booleans |
nts Online demo source code :
https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/guava/IntsTest.java
doubles Online demo source code :
https://github.com/src/main/java/com/wmx/guava/DoublesTest.java
booleans Online demo source code :
https://github.com/src/main/java/com/wmx/guava/BooleansTest.java
The same applies to other types .
JDK String helper class
1、Strings Class provides a few commonly used string Utilities .
Online demo source code :https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/guava/StringsTest.java
2、Joiner It's a connector , Used to connect to java.lang.Iterable、java.util.Iterator、java.lang.Object[] The elements in .
Online demo source code :https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/guava/JoinerTest.java
3、Splitter It's a divider , Used to segment character sequences java.lang.CharSequence.
Online demo source code :https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/guava/SplitterTest.java
4、CharMatcher Character matchers , Used to match characters , Can be CharMatcher Considered to represent a specific class of characters , Such as numbers or blanks . Be careful :CharMatcher Only deal with char value .
Online demo source code :https://github.com/wangmaoxiong/apache-study/blob/master/src/main/java/com/wmx/guava/CharMatcherTest.java
Stopwatch Stopwatch
1、google Stop watch Stopwatch comparison Spring framewrk core package and apache commons lang3 The stopwatch in the bag is the most convenient to use .
2、 This class is not thread safe .
/**
* Stopwatch createStarted(): establish ( And start the ) A new stopwatch , Use System#nanoTime As its time source .
* Stopwatch createUnstarted(): establish ( But it doesn't start. ) A new stopwatch , Use System#nanoTime As its time source .
* long elapsed(TimeUnit desiredUnit): Returns the current elapsed time displayed on this stopwatch , Expressed in required time units , Any fraction is rounded down
* boolean isRunning(): If... Has been called on this stopwatch start()}, And since the last call start() Has not been called since stop(), Then return to true
* Stopwatch reset(): Set the running time of this stopwatch to zero , And put it in the stop state .
* Stopwatch start(): Start stopwatch , If the stopwatch is already running , be IllegalStateException
* Stopwatch stop(): Stop the stopwatch , Future reads will return the fixed duration elapsed so far .
* tring toString(): Returns the string representation of the current runtime , such as 2.588 s,106.8 ms
*/
@Test
public void testStopwatch() throws InterruptedException {
SecureRandom secureRandom = new SecureRandom();
Stopwatch stopwatch = Stopwatch.createStarted();
int nextInt = secureRandom.nextInt(2000);
System.out.println(" Mission 1 Budget time :" + nextInt);// Mission 1 Budget time :81
TimeUnit.MILLISECONDS.sleep(nextInt);
System.out.println("\t Mission 1 The actual time consuming :" + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "( millisecond )");// Mission 1 The actual time consuming :563( millisecond )
stopwatch.reset().start();
nextInt = secureRandom.nextInt(4000);
System.out.println(" Mission 2 Budget time :" + nextInt);// Mission 2 Budget time :1591
TimeUnit.MILLISECONDS.sleep(nextInt);
System.out.println("\t Mission 2 The actual time consuming :" + stopwatch.toString());// Mission 2 The actual time consuming :1.592 s
stopwatch.reset().start();
nextInt = secureRandom.nextInt(3000);
System.out.println(" Mission 3 It's expected to take :" + nextInt);// Mission 3 It's expected to take :1964
TimeUnit.MILLISECONDS.sleep(nextInt);
System.out.println("\t Mission 3 The actual time consuming :" + stopwatch.stop().toString());// Mission 3 The actual time consuming :1.965 s
}I think it's good , Just use it !
Copyright notice : This paper is about CSDN Blogger 「 Chiyou descendants 」 The original article of , follow CC 4.0 BY-SA Copyright agreement , For reprint, please attach the original source link and this statement . Link to the original text :https://blog.csdn.net/wangmx1993328/article/details/103533060
Recent hot article recommends :
1.1,000+ Avenue Java Arrangement of interview questions and answers (2022 The latest version )
2. Explode !Java Xie Cheng is coming ...
3.Spring Boot 2.x course , It's too complete !
4. Don't write about the explosion on the screen , Try decorator mode , This is the elegant way !!
5.《Java Development Manual ( Song Mountain version )》 The latest release , Download it quickly !
I think it's good , Don't forget to like it + Forward !
边栏推荐
- Netdata data data persistence configuration
- 想做个答题类的微信小游戏?读这篇文章就够了
- Huawei machine learning service speech recognition function enables applications to paint "sound" and color
- 技术分享| 融合调度中的广播功能设计
- 服务器上的RTC时间与世界时间不一致解决办法
- 如何统计项目代码(比如微信小程序等等)
- leetcode 522. Longest special sequence II
- 开户可以在网上开么?能安全吗
- Clickhouse database uses JDBC to store milliseconds and nanoseconds
- *打卡算法*LeetCode 146. LRU 缓存 算法解析
猜你喜欢

UI file introduction in QT

Three best practices help enterprises improve supply chain security

DeeCamp2022正式开营!李开复、张亚勤亲授大师课 | 创新事

【无标题】安装依赖报错:Refusing to install package with name “***“ under a package

Yolo series combs (IX) first taste of newly baked yolov6

Schiederwerk power supply maintenance smps12/50 pfc3800 analysis

Force buckle: merging two ordered linked lists

RT thread memory management

揭秘!付费会员制下的那些小心机!

Use Gerrit + Zadig to realize trunk development and trunk publishing (including byte flying Book Practice)
随机推荐
mysql调优
leetcode 522. 最长特殊序列 II
Code tidiness learning notes
思科模拟器简单校园网设计,期末作业难度
代码整洁之道学习笔记
神经网络各个部分的作用 & 彻底理解神经网络
Windwos10 installing sshd service
Use Gerrit + Zadig to realize trunk development and trunk publishing (including byte flying Book Practice)
服务器监控netdata面板配置邮件服务
CVPR2022 | 可精简域适应
使用 Gerrit + Zadig 实现主干开发主干发布(含字节飞书实践)
自主可控再下一城!首套国产ARTIQ架构量子计算测控系统发布
Clickhouse database uses JDBC to store milliseconds and nanoseconds
技术分享| 融合调度中的广播功能设计
YOLO系列梳理(九)初尝新鲜出炉的YOLOv6
bind原理及模拟实现
The former security director of Uber faced fraud allegations and concealed the data leakage event
How can the sports app keep the end-to-side background alive to make the sports record more complete?
项目管理复习题
cnpm报错‘cnpm‘不是内部或外部命令,也不是可运行的程序或批处理文件