Guava study notes

Guava study notes

1, Collection type



  1. Guava provides Multiset. Although the name has Set, it can add duplicate elements;
  2. Multiset can be regarded as a combination of ArrayList and Map
  3. Multiset is an ArrayList without element order restrictions
  4. A Map with key as element and value as count is provided
MapCorresponding multisetWhether null elements are supported

Easy to use method:

Multiset<String> multiset = HashMultiset.create();// establish
multiset.count("str");// Query the number of STRs in the collection
multiset.addAll(list);// Add an object to the collection (list mapHashMultiset is OK)
Set<String> set = multiset.elementSet();//  Go back to a set
multiset.setCount("str",5);// Set the number of STRs in the collection to increase as much as possible and decrease as little as possible

Supports efficient acquisition of subsets of a specified range

Supports efficient acquisition of subsets of a specified range

Easy to use method:

SortedMultiset<String> multiSet = TreeMultiset.create();// establish
multiSet.firstEntry();// Get the first element
multiSet.lastEntry();// Get the last element
SortedMultiset<String> newMultiSet = multiSet.subMultiset("str1", BoundType.OPEN, "str3", BoundType.CLOSED);// After str1 is specified, the first start str3 ends, and a new collection is generated

Guava provides us with a Multimap, which can be used to map multiple values with a Key

Multimap multimap = ArrayListMultimap.create();

multimap.putAll(multimap1);// Add multiple value s to a key
System.out.println("a-->" + multimap.get("a"));// [a_value1, a_value2] putAll can be added to list and map

multimap.remove("a", "a_value1");// Delete the value of one key at a time
multimap.replaceValues("a", Lists.newArrayList("b1_value","b2_value"));// Replace a with value
multimap.removeAll("a");// Delete all values of key
Map<String,List<String>> map = multimap.asMap();// Convert multimap to Map
realizationKey behavior is similarValues behave similarly

In JDK, if we want to maintain a two-way Map, we need to define two maps to store, and the two maps should be changed at the same time

Guava provides BiMap, which is a special Map that can reverse key values

BiMap biMap = HashBiMap.create();
biMap.put("a", "123");
System.out.println(biMap);// {a=123}
System.out.println(biMap.inverse());// {123=a}
biMap.put("b","123");// Throw exception value already present: 123

In JDK, when you need to map a key to a key value pair, you need to write map < K, map < K, V > >. This writing method is also not friendly and inconvenient to maintain

Guava provides tables to solve this scenario, which is actually a row, column and value structure

Table<String, String, String> table = HashBasedTable.create();
//  row colum value
System.out.println("row-->" + table.row("a1"));// {b1=c1}
System.out.println("column-->" + table.column("b1"));// {a1=c1, a2=c2}

When checking the results, key will do a de duplication


ClassToInstanceMap is a special Map: its key is a type, and its value is an object of the type to which the key refers

ClassToInstanceMap classToInstanceMap = MutableClassToInstanceMap.create();
System.out.println(classToInstanceMap.getInstance(Integer.class));// 789

Immutable Collections immutable collections

What is an immutable set

After the object is created, all States and attributes cannot be modified in the whole life cycle

Similarly, an immutable set means that after the set is created, the objects in the set cannot be modified

Why do I need immutable sets

It makes concurrent processing easier.

Generally, when dealing with concurrency, we Lock shared resources, such as synchronize and Lock, and let threads process them serially. In fact, if you think about it carefully, there will be concurrency problems because there will be resource contention between threads. Modifying shared resources will affect other threads.

Shared resources cannot be modified by any thread, so threads will not affect each other at all. Naturally, it is thread safe!

Eliminate side effects.

After creation, the attributes and status cannot be changed, and the data will not be modified unexpectedly

Immutable objects can reduce the probability of collection errors.

common method

copyOf() method

List<String> unList = Collections.unmodifiableList(list);
unList.add("d");// Adding an element to an immutable List will report an error

of method

ImmutableList<String> immutableList = ImmutableList.of("a","b","c");

Builder method

List<String> list  = new ArrayList<String>();
ImmutableList<String> immutableList = ImmutableList.<String>builder().addAll(list).add("d").build();

2, Common collection tool classes


common method
  • asList() turns a data group into a list
  • Partition (list, int size) separates the list into multiple lists according to the specified size
  • Cartesian product (list < > lists) gets the Cartesian set of multiple lists
  • charactersOf(String str) converts a string into a character set
  • Reverse (list) reverses the list


common method
  • Cartesian product (set < > sets) Cartesian set
  • Combinations (set, final int size) are arranged and combined according to the specified size
  • Difference (final set Set1, final set <? > set2) the difference set of two sets
  • Intersection (final set Set1, final set <? > set2)
  • Filter (set unfiltered, predict <? Super E > predict) filter
  • Powerset (set) gets all subsets that a set can be separated into
  • Union (final set <? Extensions E > Set1, final set <? Extensions E > set2) union


common method
  • Maps.newConcurrentMap();. . .
  • Asmap (set, function < > function) set to map
  • Difference (map < K, V > left, map < K, V > right) calculates the difference of map
  • Filterentries (map < K, V > unfiltered, predict <? Super Entry < K, V > > entrypredicate) are filtered through entries
  • FilterKeys (map < K, V > unfiltered, final predict <? Super k > keypredict) are filtered through the Key

3, Guava cache

Introduction to Guava cache

In order to limit the use of memory, Guava Cache usually sets automatic recycling

Usage scenario of Guava cache

  • To trade space for time is to trade memory consumption for improved read performance
  • It is predicted that some data will be queried frequently
  • The data stored in the cache will not exceed the memory space

Common Cache parameters

  • . initialCapacity(1024) / / initial capacity
  • maximumSize maximum number of records, the number of stored data
  • maximumWeight maximum capacity, size of stored data
  • How long after expireAfterWrite is written, the data expires
  • expireAfterAccess data expires when it has not been accessed for a long time

common method

Recycling strategy

  • How long does expireAfterWrite write take to recycle
  • How long does expireAfterAccess recycle without being accessed

Guava Cache also supports reference level based recycling, which is Java specific

Data clearing listener

public void onRemoval(RemovalNotification<Object, Object> notification) {
       System.out.println("[" +notification.getKey() + ":" + notification.getValue() + "] Deleted");

statistical information



4, String tool class

Joiner method

Joiner is used to connect strings. It can connect multiple strings with specified characters

ArrayList<String> list = Lists.newArrayList("1", "2", "3", "4", "5");
System.out.println(Joiner.on(",").join(list));// 1,2,3,4,5

// skipNulls will skip null values. When there is a null value, the join method will report a null pointer exception
System.out.println(Joiner.on(",").skipNulls().join(list));// 1,2,3,4,5

// useForNull will programmatically specify a null value
System.out.println(Joiner.on(",").useForNull("%").join(list));// 1,2,%,3,4,5

// Method used by withKeyValueSeparator to connect map
Map<String,String> map = Maps.newHashMap();
System.out.println(Joiner.on(",").withKeyValueSeparator(":").join(map));// 1:abc,2:def,3:ghi

Splitter method

System.out.println(Splitter.on(",").splitToList("a,b,c"));// [a, b, c]

CharMatcher method

CharMatcher is used to handle complex string operations. It is generally used to find and process matching strings

Query method
  • is(char c): returns the Matcher that matches the specified character
  • isNot(char c): returns a Matcher that does not match the specified character
  • Anyof (charsequence): returns a Matcher that matches any character in the sequence
  • Noneof (charsequence): returns a Matcher that does not match any character in the sequence
  • Inrange (char startinclusive, char endinclusive): returns the Matcher of any character in the matching range
  • Forpredicate (predicate <? Super charger > predicate): returns the Matcher that uses the predict's apply() to determine the match
  • and(CharMatcher other): returns the Matcher combined with other matching conditions to judge
  • or(CharMatcher other): returns the Matcher to judge by combining or with other matching conditions
Methods of processing query results
  • Remove from (charsequence): deletes the matched characters in the sequence and returns
  • Retain from (charsequence): retain the matching characters in the sequence and return
  • Replacefrom (charsequence, char replacement): replaces the matched characters in the sequence and returns
  • Trimfrom (charsequence): delete the characters that match the beginning and end and return
  • Trimleadingfrom (charsequence): deletes the first matched character
  • Trimtrailingfrom (charsequence): deletes the character that matches the tail
  • Collapsefrom (charsequence, char replacement): replace the matched group (continuously matched characters) with replacement
  • Trimandcollapsefrom (charsequence, char replacement): replace
String str = " uahfdsiudsufhud sJNjn hji  9123BHG91284 hdSas 8ds";

// inRange() search condition retainFrom to extract the corresponding letter
System.out.println(CharMatcher.inRange('a', 'z').retainFrom(str));// uahfdsiudsufhudsjnhjihdasds

// digit() queries all numbers and removeFrom() removes the corresponding data
System.out.println(CharMatcher.digit().removeFrom(str));//  uahfdsiudsufhud sJNjn hji  BHG hdSas ds


  • Charsets.UTF_8
  • Charsets.ISO_8859_1
  • Charsets.US_ASCII
  • Charsets.UTF_16
  • Charsets.UTF_16BE
  • Charsets.UTF_16LE


  • CaseFormat is a utility class that provides conversion between different ASCII character formats
  • You can use CaseFormat to convert hump rules
String str = "hello_world";
System.out.println(, str));// helloWorld
System.out.println(, str));// HelloWorld

Tags: Java

Posted on Fri, 08 Oct 2021 05:47:16 -0400 by LanceT