Learn -guava

Guava

Guava project consists of a number by Google Java projects rely extensively on the core libraries
such as: collection [collections], the cache [caching], native type support [primitives support], concurrency library [concurrency libraries], Common Annotations [common annotations], character processing string [string processing], I / O and the like.

guava similar Apache Commons toolset

Guava benefits

Standardization - Guava library is hosted by Google
and efficient - reliable, fast and efficient expansion of JAVA standard library
optimization is highly optimized library of -Guava


Optional

guava is similar to Java 8 new Optional Optional classes are used to handle null, but guava is an abstract class that implements class Absent and Present, and java.util is the final class. Wherein a portion of the name is the same method.
google's guava library provides an interface to the Optional null rapid failure that made a layer of packaging on possibly null objects when using the Optional static method of, if the incoming parameter is null then a NullPointerException is thrown.

Preconditions

Preconditions class of guava base package provided for easy verification of the parameters do, he provide the following method:

  • checkArgument accepts a boolean parameter and an optional errorMsg parameters, this method is used to determine whether the parameters meet certain conditions, in line with what conditions google guava does not care, does not meet the conditions when IllegalArgumentException will be thrown
  • checkState and checkArgument parameters and achieve substantially the same, from the literal meaning we can know that this method is used to determine whether the correct state, if the state is incorrect will throw an IllegalStateException
  • checkNotNull method used to determine whether the argument is not null, null pointer is null if NullPointerException exception is thrown
  • checkElementIndex method is used to determine the user's incoming array index or list index position, whether it is legitimate, if not legitimate throws IndexOutOfBoundsException
  • checkPositionIndexes role and checkElementIndex method similar to the method except for this method is the index range from 0 to the size including size, the size does not include the above method.

Joiner

Joiner provides various ways to handle strings join operation objects.
Examples Joiner's immutable and therefore thread-safe.

  • on: the development of stitching symbol
  • skipNulls (): ignore NULL, returns a new instance Joiner
  • useForNull ( "Hello"): NULL place are replaced with the string "Hello"

Splitter

Splitter can be split in accordance with a specified string delimiter strings can be set into an iterative traversal, Iterable

  • on (): Specifies the delimiter character string is divided
  • limit (): when dividing the substring reaches a limit stop dividing
  • trimResults (): removing spaces substring
  • fixedLength (): The length of the string to split
  • omitEmptyStrings (): remove empty substring
  • withKeyValueSeparator (): To split string delimiter between the key and value, the sub-divided between the delimiters string key and value default =

Connection set immutable

Immutable object has many advantages, including:

  • When the object is untrusted library calls, immutable form is secure;
  • When a plurality of threads immutable object is invoked, there is no problem of race conditions
  • Immutable set need not consider the change, thus saving time and space. All set immutable than alternative forms thereof have a better memory utilization;
  • Immutable objects because there are fixed, it can be used safely as a constant.

Create an immutable set of methods:

  • copyOf method as ImmutableSet.copyOf (set);
  • of methods, such as ImmutableSet.of ( "a", "b", "c") or ImmutableMap.of ( "a", 1, "b", 2);
  • Builder tool

New collections

  • Multiset
    disorder but may be repeated Multiset appears to be a Set, but in essence it is not a Set, it does not inherit the Set interface, it inherits Multiset interface extensions provided with repeated elements, and provides a variety of practical ways to deal with this elements appear in the collection.
    Multiset comes with a useful feature is the ability to track the number of each object.

  • Multimap
    a key Map multivalued
    Multimap can easily be mapped to a plurality of key values. In other words, Multimap a general manner the key mapped to any number of values. E.g:
Multimap<String,Integer> map= HashMultimap.create(); 
//Multimap是把键映射到任意多个值的一般方式
map.put("a",1); 
//key相同时不会覆盖原value
map.put("a",2);
map.put("a",3);
System.out.println(map); //{a=[1, 2, 3]

Multimap provides a wealth of implementation:

achieve Key realization Value realization
ArrayListMultimap HashMap ArrayList
HashMultimap HashMap HashSet
LinkedListMultimap LinkedHashMap LinkedList
LinkedHashMultimap LinkedHashMap LinkedHashSet
TreeMultimap TreeMap TreeSet
ImmutableListMultimap ImmutableMap ImmutableList
ImmutableSetMultimap ImmutableMap ImmutableSet
  • BiMap
    bidirectional Map
    We know that Map is a key-value mapping, this mapping is mapped to the key value, but also a Map BiMap first, he is unique in that not only provide the key to value mapping, but also to provide value key mapping , so it is bidirectional the map
    the map value BiMap key pairs may be obtained by a method inverse ().
    BiMap achieve common are:
  • HashBiMap: key collection and collection value has achieved HashMap
  • EnumBiMap: key and value must be enum type
  • ImmutableBiMap: non-modifiable BiMap

  • The Table
    the Table It has two supports all types of keys: "row" and "column."
    Table data structure may be implemented using a two-dimensional matrix, the matrix may be a dilute slip.
    Set operations: intersection, difference, and sets

Set<Integer> set1= Sets.newHashSet(1,2,3,4,5);
Set<Integer> set2=Sets.newHashSet(3,4,5,6);
                    
Sets.SetView<Integer> inter=Sets.intersection(set1,set2); //交集       
System.out.println(inter);
Sets.SetView<Integer> diff=Sets.difference(set1,set2); //差集,在A中不在B中       
System.out.println(diff);
                                
Sets.SetView<Integer> union=Sets.union(set1,set2); //并集       
System.out.println(union);

Cache

Cache In many scenes are quite useful. For example, calculation or retrieves a value of the cost is high, and require more than one access to the same time of the input value, you should consider using the cache.
Guava Cache and ConcurrentMap very similar, but not exactly the same. The most basic difference is that all the elements have been preserved ConcurrentMap will be added until explicitly removed.
Relatively, Guava Cache memory footprint in order to limit, usually set to automatic recovery element. In some scenarios, although LoadingCache not recycled elements, it is also very useful, because it will automatically load the cache.
Guava Cache memory is a full realization of the local cache, it provides a thread-safe implementation mechanism
Generally speaking, Guava Cache apply to: Would you like to consume some memory space to increase speed. You expect certain key will be queried more than once.
The amount of data stored in the cache memory not exceeded. (Guava Cache is a local caching a single application runtime that it does not store data to a file or to an external server..)
The Guava Cache There are two ways to create:

  • cacheLoadercallable callback
  1. LoadingCacheDemo:
LoadingCache<String,String> cache= CacheBuilder.newBuilder()
         .maximumSize(100) //最大缓存数目
         .expireAfterAccess(1, TimeUnit.SECONDS) //缓存1秒后过期               
         .build(new CacheLoader<String, String>() {     
            @Override       
            public String load(String key) throws Exception {
                                return key; 
            }   
          });
  1. CallbackDemo :
Cache<String,String> cache= CacheBuilder.newBuilder()
               .maximumSize(100)
               .expireAfterAccess(1, TimeUnit.SECONDS)
               .build();

Guess you like

Origin www.cnblogs.com/zd-blogs/p/12015810.html