01, past life

Hi, I’m Guava.

In 1995, my elder brother, Java, was born. After 20 years of development, it has become the most popular programming language in the world, so let me say “one” unfairly.

Although he is often subjected to all kinds of ridicule, but he has not stopped the pace of progress. In addition to his constant evolution, his brothers, big and small, are constantly being updated and iterated. I was born under such a background. I am easy to use and a very good complement to my brother. It can be said that whenever you have a project using my brother as the development language, you can almost see my presence.

I’m open-source by Google and currently have 39.9K followers on GitHub to prove my popularity.

My body mainly contains these commonly used modules: Collections, Caching, Primitives support, Concurrency Libraries, Common Annotations , string processing, I/O, etc. The new VERSION of the JDK has directly introduced me, you can imagine how good I am, can not help but be proud.

Let’s just say that learning how to use me will make you happier and write more elegant code!

02. Introduce Guava

If you want to use me in your Maven project, you will need to import my dependencies in the POM.xml file.

< the dependency > < groupId > com. Google. Guava < / groupId > < artifactId > guava < / artifactId > < version > 30.1 jre < / version > </dependency>Copy the code

The JDK version must be at least 8.

03. Basic Tools

Doug Lea, author of the java.util.Concurrent package, once said, “Null sucks.” Tony Hoare, Turing prize-winning author of quicksort and, of course, creator of NULL, said something similar: “I lost a billion dollars using NULL.” For this reason, I use Optional to represent objects that may be null.

A code example is shown below.

Optional<Integer> possible = Optional.of(5);
possible.isPresent(); // returns true
possible.get(); // returns 5
Copy the code

My brother added the Optional class in JDK 8, obviously borrowing from me, but his is a little different from mine.

  • My Optional is abstract, which means I can have subclass objects; My eldest brother’s is final, meaning there are no subclass objects.

  • My Optional implements the Serializable interface, which can be serialized; My brother’s didn’t.

  • Some of my methods are different from my big brother’s.

In addition to adding null semantics and readability, the most important advantage of using Optional is that it is a foolproof defense. Optional forces you to think positively about missing references because you have to explicitly get a reference from Optional.

In addition to Optional, I also provide:

  • Parameter calibration
  • Common Object methods, such as objects.equals and objects.hashcode, are provided by the Objects class introduced in JDK 7, which took inspiration from me.
  • More powerful comparators

04, collections,

First of all, let me tell you why we need immutable sets.

  • Ensure thread safety. In concurrent programs, using immutable collections not only ensures thread safety, but also greatly improves concurrency efficiency (compared with concurrent locking).

  • If an object does not need to support modification operations, immutable collections save space and time.

  • Can be treated as a constant, and objects in the collection will not be changed in the future.

Why do I say that I provide Immutable collections is truly Immutable, as opposed to the Immutable collections provided in the JDK? Consider the following example.

The following code using the JDK Collections. UnmodifiableList (list) to get a collection of immutable unmodifiableList.

List list = new ArrayList();
list.add("Lei jun");
list.add("Steve Jobs");

List unmodifiableList = Collections.unmodifiableList(list);
unmodifiableList.add("马云");
Copy the code

Running the code will cause the following exception:

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1060)
	at com.itwanger.guava.NullTest.main(NullTest.java:29)
Copy the code

Fine, perform unmodifiableList. The add () when the throw UnsupportedOperationException abnormalities, explanation Collections. UnmodifiableList () returns a collection of immutable. But is it really true?

You can replace unmodifiablelist.add () with list.add().

List list = new ArrayList();
list.add("Lei jun");
list.add("Steve Jobs");

List unmodifiableList = Collections.unmodifiableList(list);
list.add("马云");
Copy the code

If you run it again, there is no error, and you will notice that there is indeed one more element in the unmodifiableList. What does that mean?

The Collections. UnmodifiableList (…). The implementation is not a true immutable set. When the original set is modified, the elements in the immutable set also change.

I’m not going to make that mistake, so let’s look at this code.

List<String> stringArrayList = Lists.newArrayList("Lei jun"."Steve Jobs");
ImmutableList<String> immutableList = ImmutableList.copyOf(stringArrayList);
immutableList.add("马云");
Copy the code

Try immutableList. Add will throw an UnsupportedOperationException (). I’ve discarded the add() method in the source code.

  /**
   * Guaranteed to throw an exception and leave the collection unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @CanIgnoreReturnValue
  @Deprecated
  @Override
  public final boolean add(E e) {
    throw new UnsupportedOperationException();
  }
Copy the code

The immutableList does not change when stringArrayList.add() attempts to modify the original collection.

In addition to immutable collections, I also provide new collection types, such as:

  • Multiset, which can add equal elements more than once. When viewed as a normal Collection, a Multiset behaves like an unordered ArrayList; When a Multiset is thought of as Map

    , it also provides query operations that meet performance expectations.
    ,>

  • Multimap, which makes it easy to map a key to multiple values.

  • BiMap, a special kind of Map, can be inverted with inverse()

Key value mapping of BiMap

; Values are guaranteed to be unique, so values() returns a Set instead of a normal Collection.
,>

05, string processing

A string represents an immutable sequence of characters that cannot be changed after creation. In our daily work, the use of strings is very frequent, skilled operation can greatly improve our work efficiency.

I provided a Joiner, which joins sequences of strings together using delimiters. The following code will return “Lei Jun; You can use the useForNull(String) method to replace NULL with a String instead of ignoring null as skipNulls() does.

Joiner joiner = Joiner.on("; ").skipNulls();
return joiner.join("Lei jun".null."Steve Jobs");
Copy the code

I also provided a Splitter — Splitter, which splits a sequence of strings according to a specified delimiter.

Splitter.on(', ')
        .trimResults()
        .omitEmptyStrings()
        .split("Lei Jun, Steve Jobs, The Silent King.");
Copy the code

06, caching,

Caching can be quite useful in many scenarios. You should be aware that retrieving a value is expensive, especially if you need to retrieve the value more than once, so you should consider caching.

The Cache I provide is similar to ConcurrentMap, but not exactly the same. The basic difference is that ConcurrentMap keeps all added elements until they are explicitly removed. In contrast, the caches I provide are usually set to recycle elements automatically to limit memory footprint.

If you are willing to consume some memory space to speed things up, you can expect certain keys to be queried more than once, and the total amount of data in the Cache will not exceed memory capacity, you can use the Cache.

Let me give you an example.

@Test
public void testCache(a) throws ExecutionException, InterruptedException {

    CacheLoader cacheLoader = new CacheLoader<String, Animal>() {
        // If no element is found, this is called
        @Override
        public Animal load(String s) {
            return null; }}; LoadingCache<String, Animal> loadingCache = CacheBuilder.newBuilder() .maximumSize(1000) / / capacity
        .expireAfterWrite(3, TimeUnit.SECONDS) // Expiration time
        .removalListener(new MyRemovalListener()) // Invalid listener
        .build(cacheLoader); //
    loadingCache.put("Dog".new Animal("Prosperous wealth.".1));
    loadingCache.put("Cat".new Animal("Tom".3));
    loadingCache.put("The Wolf".new Animal("Big Big Wolf".4));

    loadingCache.invalidate("Cat"); // Manual failure

    Animal animal = loadingCache.get("The Wolf");
    System.out.println(animal);
    Thread.sleep(4 * 1000);
    // The Wolf has automatically passed, the value is null error
    System.out.println(loadingCache.get("The Wolf"));
}

/** * cache removal listener */
class MyRemovalListener implements RemovalListener<String.Animal> {

    @Override
    public void onRemoval(RemovalNotification<String, Animal> notification) {
        String reason = String.format("key=%s,value=%s,reason=%s", notification.getKey(), notification.getValue(), notification.getCause()); System.out.println(reason); }}class Animal {
    private String name;
    private Integer age;

    public Animal(String name, Integer age) {
        this.name = name;
        this.age = age; }}Copy the code

The load method will be called if there is no hit in the cache. I returned null. This will return null for the key if there is no hit.

MyRemovalListener is the listener class that listens when the cache element fails. OnRemoval is automatically called when the cache element fails. Note that this method is synchronous, and if it takes a long time, it will block until processing is complete.

LoadingCache is the main operation object of the cache. The commonly used methods are put and GET.

07, the end

The above introduces the functions I think most commonly used, as Google open source Java development core library, I feel practical or very high (otherwise? Hey hey hey). Introducing it into your project will not only quickly implement some commonly used functions in development, but also make the code more elegant and concise.

I think it applies to every Java project, but the rest of the functionality, such as hashing, event bus, math, reflection, is up for you to discover.

In addition, I have prepared a Chinese version of the official document for you (see part of the contents in the picture above), a total of 190 pages, written in great detail, strongly suggest you download a copy through the following way and put it on the desktop!

Link: pan.baidu.com/s/1hrfaArC3… Password: 684 a

Recommended reading:

Teach yourself Java, how long before you can find a job?

After reading the notes from senior students at Google, I decided to solve the 101 Leetcode algorithm problems by hand in 2021

If the content is helpful to you, please give me a thumb-up, pen core ~, you are the most beautiful you are the most handsome, you will be rich in 2021.