Java google's open source development tool for java development - guava introductory manual

Keywords: Programming JDK Java Google

1. Introduction

There are many difficult examples of Java class libraries, Collection must be one of them.Google first proposed the Guava library as an extension of the Java Collection to improve development efficiency.Over time, it has covered all aspects of Java development, and in Java 8, you can see that many API s are still learning from Guava.

The next few examples compare development using Guava with native JDK:

2. Contrast between jdk1.8 and guava

1. Initialize the collection

//JDK
List<String> list = new ArrayList<String>(); 
list.add("a");
list.add("b");
list.add("c");
list.add("d");

//Guava
List<String> list = Lists.newArrayList("a", "b", "c", "d");

2. Read the contents of the file

//JDK is long enough to search for itself

//Guava
List<String> lines = Files.readLines(file, Charsets.UTF_8);

3. New types of collections

Guava provides some new collection type simplification code for common scenarios in development.

Multiset

We often encounter a type of statistical requirement that counts the number of times an object (such as a string) occurs in a set, then there is the following code:

//jdk
Map<String, Integer> counts = new HashMap<String, Integer>();
for (String word : words) {
    Integer count = counts.get(word);
    if (count == null) {
        counts.put(word, 1);
    } else {
        counts.put(word, count + 1);
    }
}

This code looks a little ugly and error prone.Guava provides a new collection type, Multiset.As the name implies, the same elements can exist in a Set at the same time:

//guava
Multiset<String> multiset = HashMultiset.create();

multiset.add("a");
multiset.add("a");
multiset.add("b", 5);//add "b" 5 times

System.out.println(multiset.elementSet());//[a, b]
System.out.println(multiset.count("a"));//2
System.out.println(multiset.count("b"));//5
System.out.println(multiset.count("c"));//0

Multiset is much like an ArrayList because it allows duplicate elements, but there is no order between them; it also has some of the features of Map < String, Integer >.But essentially it's also a true set type - the concept used to express a mathematical "multiple set". This example just corresponds to Map.

MultiMap

You must have encountered implementing a collection during development: Map<K, List<V> Map<K, Set<V> to represent a Key's corresponding element is a collection that can be viewed from two perspectives:

If you use the Collection provided by JDK to achieve similar functionality, there must be code like the statistics in the previous section: when you add an element, look for the corresponding List of that element in Map first, or create a new List object if it does not exist.

//guava
Multimap<String, Integer> multimap = ArrayListMultimap.create();
multimap.put("a", 1);
multimap.put("a", 2);
multimap.put("a", 4);
multimap.put("b", 3);
multimap.put("c", 5);

System.out.println(multimap.keys());//[a x 3, b, c]
System.out.println(multimap.get("a"));//[1 ,2, 4]
System.out.println(multimap.get("b"));//[3]
System.out.println(multimap.get("c"));//[5]
System.out.println(multimap.get("d"));//[]

System.out.println(multimap.asMap());//{a=[1, 2, 4], b=[3], c=[5]}

4. Collection Tool Class

Static Creation Method

Prior to JDK 7, creating generic collections was tedious:

//jdk 1.7
List<TypeThatsTooLongForItsOwnGood> list = new ArrayList<TypeThatsTooLongForItsOwnGood>();

Guava provides a static way to infer generic types:

//guava
List<TypeThatsTooLongForItsOwnGood> list = Lists.newArrayList();
Map<KeyType, LongishValueType> map = Maps.newLinkedHashMap();

Of course, generic type inference is already supported in JDK 8:

//jdk 1.8
List<TypeThatsTooLongForItsOwnGood> list = new ArrayList<>();

In addition to providing static construction methods, Guava also provides a series of factory class methods to support collection creation:

//guava
Set<Type> copySet = Sets.newHashSet(elements);
List<String> theseElements = Lists.newArrayList("alpha", "beta", "gamma");

Sets

We often need to manipulate Sets and perform operations such as intersection and complement, which are provided by the Set s class:

  • union(Set, Set)//merge
  • intersection(Set, Set)//union set
  • difference(Set, Set)//non-union set part
  • symmetricDifference(Set, Set)//
Set<String> wordsWithPrimeLength = ImmutableSet.of("one", "two", "three", "six", "seven", "eight");
Set<String> primes = ImmutableSet.of("two", "three", "five", "seven");

// contains "two", "three", "seven"
SetView<String> intersection = Sets.intersection(primes, wordsWithPrimeLength); 
// I can use intersection as a Set directly, but copying it can be more efficient if I use it a lot.
return intersection.immutableCopy();

Primitives

The basic types (Primitive) in Java include byte, short, int, long, float, double, char, boolean.

Some of the corresponding tool classes in Guava include Bytes, Shorts, Ints, Longs, Floats, Doubles, Chars, Booleans.Now take Ints as an example to demonstrate some common methods:

System.out.println(Ints.asList(1,2,3,4));
System.out.println(Ints.compare(1, 2));
System.out.println(Ints.join(" ", 1, 2, 3, 4));
System.out.println(Ints.max(1, 3, 5 ,4, 6));
System.out.println(Ints.tryParse("1234"));

Hashing

Writing a Hash hash algorithm is complicated in Java, but it's very simple in Guava:

public static String md5(String str) {
    return Hashing.md5().newHasher()
            .putString(str, Charsets.UTF_8)
            .hash()
            .toString();
}

3. Personal Summary

Guava is a very useful modern library that is highly recommended in Java projects to replace some of the subprojects of Apache Commons (such as Lang, Collection, IO, etc.). In addition to some of the most common features described here, it also includes caching, networking, IO, functional programming, and so on (where Stream and Lambda expressions can be used in Java 8 for functional programming).And so on).

Posted by penguinmasta on Sun, 24 Nov 2019 00:13:06 -0800