Blog address: sourl.cn/CXgw9P

In daily development, Black brother often needs to use Java to provide collection classes to complete various requirements. Java collection classes, while very powerful and useful, are a little weak in their functionality.

For example, little black brother recently received a demand, from the input of a document, count the number of occurrences of a keyword. The code is as follows:

Although this requirement can be easily handled using Map, I still feel that this method is a bit clumsy and will cause NPE exceptions if it is not called null.

If functionality is needed in many places, we can abstract it away and encapsulate it as a utility class.

But the above function we do not need to package, a from Google open source tool class -Guava, can easily solve the above statistical problems.

Guava is introduced

Guava is a Google open source utility class that contains many of the core classes that Google’s internal Java projects rely on. Guava extends the Java infrastructure, such as collections and concurrency, and adds other powerful features, such as caching and limiting traffic.

In addition, some Guava classes, such as Optional, were even learned by Java developers and later added to the JDK.

At present, Guava Github warehouse has 36K star, which shows the popularity of Guava.

Guava core functions include a number of modules, today xiaohei mainly take you to play Guava collection class.

Extended set class

Guava creates a lot of new collection types that the JDK doesn’t have, but that are obviously useful in our daily lives. These new types use the JDK collections interface specification, so they are used in much the same way as the JDK collections framework without much difficulty.

Multiset

The first time I saw Multiset, I thought it was a subclass of Set. In fact, this “Set” is just a mathematical concept of a Set.

Multiset inherits the JDK Collection interface. We can add the same element multiple times. In addition, the Multiset Max will count the elements.

The initial problem can be easily solved using multisets.

Using Multiset simplifies the code, and you don’t have to worry about new NPES anymore.

Like the JDK collection classes, Multiset has many subclasses.

Multiset

is Map

, but Multiset is not a subclass of Map. It is a pure Collection subclass.
,>

Multimap

Hei sometimes uses Map

in business requirements to implement the following requirements.
,list

A - > [1, 2, 3] - > 4 b, c - > (6, 5)Copy the code

Using the Map + List structure is unwieldy and cumbersome to code. Multimap is the latest iteration of Guava to solve this problem.

The code for using Multimap is as follows:

Here, HashMultimap subclass HashMultimap is used. Its behavior is similar to Map

>, that is, Value cannot be repeated inside the Set. If we need to save duplicate elements we can use an ArrayListMultimap.
,set

There are other subclasses of Multimap, as shown below:

BiMap

BiMap can be used to implement bidirectional mapping of key-value pairs, so that we can find the Value of the pair by Key and find the Key by Value.

Using a Map for this requirement would have forced us to use two maps, maintain a bidirectional relationship, and keep any changes in sync.

Modify the above code using BiMap:

It is important to note that the BiMap#put method cannot add repeating elements. If it does, it will throw an error. If a particular value must be replaced, use the BiMap#forcePut instead.

Type on the blackboard and write this down. Black brother in the process of use, stepped on this hole.

BiMap also has various implementation classes:

Other extension collection classes

Guava also provides other collection classes, but these classes are a little more complicated to use and haven’t been used in business code yet. Here are some of the classes for those interested in learning more about them.

  • Table
  • ClassToInstanceMap
  • RangeSet
  • RangeMap

Collection utility class

In addition to the new collection classes mentioned above, Guava provides generic utility classes:

These utility classes need to use methods, we can quickly create collections, split collections, transform collections and so on.

Quickly create a collection instance

Using utility classes, we can quickly create collections. Such as:

List<String> list=Lists.newArrayList();
Set<String> set=Sets.newHashSet();
Map<String,String> map=Maps.newHashMap();
Copy the code

Compared to the new collection method, the Guava method is simpler to create.

List<String> list=new ArrayList<String>();
Set<String> set=new HashSet<String>();
Map<String,String> map=new HashMap<String, String>();
Copy the code

The Guava utility class intelligently derives the List generics, eliminating the need to write generics on both sides.

You can also specify the initialization size of the collection class.

Lists.transform

Instead of a cumbersome for loop, the Lists#transform method transforms the elements to create a new collection class.

But we have to be careful with this method.

Lists#transform uses a lazy loading mechanism inside of Lists#transform. Only when the fetched elements are called, such as result.get, will Function actually fetch the elements from the source List and transform them accordingly. Each time an element is fetched, it will be transformed using function.

So use Lists#transform to get the List is just a view of the source List, and any changes to the elements of the source List will be reflected in the created List. Any changes made to elements in the List after creation will not take effect. The next time you read the element, you’ll find that the modified version is missing…

If you have the need, you can create a new collection as follows:

Before JDK8, this method was often used to convert elements in a List. If you use JDK8, however, Stream programming is recommended.

Difference set of intersection union

Sets provides several methods for quickly finding the intersection, union, and difference of two Sets.

Immutable set

An Immutable set, as the name implies, cannot be modified. When you initially create an immutable collection, you need to pass in the data source. After you create the collection, you can no longer modify, add, or delete elements. Otherwise, an error will be reported.

This is a defensive strategy that prevents the collection from being modified in subsequent operations and causing problems.

The advantages of immutable sets are:

  • Since immutable collections are only readable, multithreaded concurrency is naturally safe
  • Because immutable sets are fixed and immutable, they can be safely treated as constants without being modified by others on a single line
  • Immutable sets take up less memory
  • Immutable sets cannot be modified, so there is no need to worry about other programs arbitrarily modifying the set

Guava immutable collections support all JDK collections interfaces:

We can create immutable sets in the following ways, using ImmutableList as an example:

List<String> fromList=Lists.newArrayList("Thumb up"."Attention");
// Copy elements from a collection
ImmutableList.copyOf(fromList);
ImmutableList.of("Attention"."Java Geek Technology");
ImmutableList.builder().add("Attention").addAll(fromList).build();
Copy the code

conclusion

In this article, little black brother will take you to learn how to use the relevant classes of the open source tool Guava set. We are good at using these tools in daily development, instead of repeating the wheel by ourselves.

This article only introduces a few of Guava’s features, and there are a number of other features that I think are very useful in Guava. Check out the Official Guava Wiki to see how to use it.

If you still want to know about other open source tools, give a thumbs up to The little black brother, next time bring you very useful open source tools ~

Welcome to pay attention to my public account: procedures to get daily dry goods push. If you are interested in my topics, you can also follow my blog: studyidea.cn