"Turn" EVA (Guava) API quickly familiar with the use of

Source: Internet
Author: User
Tags addall

Http://www.cnblogs.com/snidget/archive/2013/02/05/2893344.html

1, outline

Let's familiarize ourselves with the melon and experience some of its APIs, divided into the following sections:

    • Introduction
    • Guava Collection API
    • Guava Basic Utilities
    • IO API
    • Cache API

2, choose a baby for God's horse?

    • Eva is the ice cream on the Java API Cake (essence)
    • Efficient and well-designed API.
    • Designed, implemented, and used by Google's developers.
    • Follow the good grammar practices of this book of efficient java.
    • Make the code more scale, concise, and simple.
    • Using the features of Java 1.5,
    • Popular APIs, dynamic development
    • It provides a number of related application classes, collections, multithreading, comparisons, strings, input and output, caches, networks, native types, math, reflection, etc.
    • Hundreds of unit tests, used by many projects, help developers focus on business logic rather than writing Java application classes
    • Save time, resources and increase productivity
    • My goal is to provide support for the basic Java features with open source code, rather than writing a
    • Apache Common Library-apache is a well-established library, but generics are not supported, Apache is useful for early Java versions (before 1.5)
    • JAVA7,JAVA8 The latest Java support for some guava APIs

The latest official version of Guava is 14.0-RC2, and this version requires java1.6 support.

The latest MAVEN coordinates are:

<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>14.0-rc2</version>
</dependency>

3, use of the collection API

3.1 Simplifying work

Can simplify the creation and initialization of the collection;

Category The original wording The writing of Guava
Collection creation

Map<string, map<string, string>> Map = new hashmap<string, map<string,string>> ();

list<list<map<string, string>>> List = new Arraylist<list<map<string,string>>> ( );

Map<string, map<string, string>> Map = Maps.newhashmap ();

list<list<map<string, string>>> List = Lists.newarraylist ();

1, simplifying the creation of collections
List<person> personlist= lists.newlinkedlist ();
Set<person> personset= Sets.newhashset ();
Map<string,person> personmap= Maps.newhashmap ();
Integer[] intarrays= Objectarrays.newarray (integer.class,10);

Collection initialization

set<string> set = new hashset<string> ();

Set.add ("one");

Set.add ("both");

Set.add ("three");

set<string> set = Sets.newhashset ("One", "one", "three");

list<string> list = Lists.newarraylist ("One", "one", "three");

map<string, string> map = Immutablemap.of ("On", "TRUE", "OFF", "FALSE");

2, simplifying the initialization of the collection
List<person> personlist2= lists.newarraylist (New person (1, 1, "a", "46546", 1, 20),

New Person (2, 1, "a", "46546", 1, 20));
Set<person> personset2= Sets.newhashset (new person, "a", "46546", 1,20),

New Person (2,1, "a", "46546", 1,20));
map<string,person> personmap2= immutablemap.of ("Hello", new person (all, "a", "46546", 1,20), "fuck", new person ( 2,1, "A", "46546", 1,20));

3.2 invariance

A big part of it is that the Google collection provides immutability, constant contrast variability:

    • Data cannot be changed
    • Thread Safety
    • No synchronization logic required
    • can be freely shared.
    • Easy to design and implement
    • Efficient memory and time

Unchanging contrast is not modifiable

Google's constant is guaranteed to be truly immutable, and non-modifiable can actually modify the data, as shown here:

set<integer> data = new hashset<integer> ();

Data.addall (Arrays.aslist (10, 20, 30, 40, 50, 60, 70, 80));

set<integer> Fixeddata = collections.unmodifiableset (data); Fixeddata-[50, 70, 80, 20, 40, 10, 60, 30]

Data.add (90); Fixeddata-[50, 70, 80, 20, 40, 10, 90, 60, 30]

How to create immutable collections:

immutableset<integer> numbers = Immutableset.of (ten , +, +, +);

Using the Copyof method

immutableset<integer> another = mmutableset.copyof (numbers);

Using the Builder method

immutableset<integer> numbers2 = immutableset.<integer>builder (). AddAll (Numbers). Add (70). Add (+). Build ();

3, creating immutable collections

Immutablelist<person> personimmutablelist=
Immutablelist.of (New Person (1, 1, "a", "46546", 1, +), new person (2, 1, "a", "46546", 1, 20));

Immutableset<person> personimmutableset=immutableset.copyof (PersonSet2);

Immutablemap<string,person> Personimmutablemap=immutablemap.<string,person>builder ()
. put ("hell", New Person ("A", "46546", 1,20)). Putall (PERSONMAP2). build ();

3.3 New collection types

The guava API provides very useful new collection types that work very nicely with existing Java collections.

The guava API provides a useful new collection type that works well with existing Java collections.

MultiMap, MultiSet, Table, BiMap, Classtoinstancemap, respectively.

Kinds Examples of writing
MultiMap

A key can be repeated map, subclasses have Listmultimap and Setmultimap, corresponding to the key by the list and set


Multimap<string, person> customersbytype =arraylistmultimap.create (); Customersbytype.put ("abc", New Person (1, 1, "A", "46546", 1, 20));

Customersbytype.put ("ABC", New Person (1, 1, "a", "46546", 1, 30));
Customersbytype.put ("ABC", New Person (1, 1, "a", "46546", 1, 40));
Customersbytype.put ("ABC", New Person (1, 1, "a", "46546", 1, 50));
Customersbytype.put ("ABCD", New Person (1, 1, "a", "46546", 1, 50));
Customersbytype.put ("ABCDE", New Person (1, 1, "a", "46546", 1, 50));

for (Person Person:customersByType.get ("abc"))
{
System.out.println (Person.getage ());
}

MultiSet

 

is not a collection, you can add duplicate elements, and you can count the number of duplicate elements, as shown in the following example:

private static void Testmulitiset () {
Multiset<integer> Multiset = Hashmultiset.create ();
Multiset.add (10);
Multiset.add (30);
Multiset.add (30);
Multiset.add (+);

System.out.println (Multiset.count ());//2
System.out.println (Multiset.size ());//4
}

Table

 

Equivalent to a map with two keys, not much explanation

private static void TestTable () {
table< Integer,integer,person> persontable=hashbasedtable.create ();
Persontable.put (1,20,new person (1, 1, "a", "46546", 1, 20));
Persontable.put (0,30,new person (2, 1, "AB", "46546", 0, 30));
Persontable.put (0,25,new person (3, 1, "abc", "46546", 0, 25));
Persontable.put (1,50,new person (4, 1, "AEF", "46546", 1, 50));
Persontable.put (0,27,new person (5, 1, "Ade", "46546", 0, 27));
Persontable.put (1,29,new person (6, 1, "ACC", "46546", 1, 29));
Persontable.put (0,33,new person (7, 1, "Add", "46546", 0, 33));
Persontable.put (1,66,new person (8, 1, "AFADSF", "46546", 1,));

//1, GET rowset
map<integer,person> rowmap= persontable.row (0);
int maxage= Collections.max (Rowmap.keyset ());

}

BiMap is a one by one mapping, you can get value by key, you can also get key by value;

private static void Testbitmap () {
Bidirectional map
Bimap<integer,string> bimap=hashbimap.create ();

Bimap.put (1, "Hello");
Bimap.put (2, "Helloa");
Bimap.put (3, "World");
Bimap.put (4, "worldb");
Bimap.put (5, "my");
Bimap.put (6, "Myc");

int value= bimap.inverse (). Get ("my");
System.out.println ("My--" +value);

}

Classtoinstancemap Sometimes, your map's key is not a type, they are many types, and you want to map them to get this type, guava provides classtoinstancemap to meet this purpose. In addition to inheriting from the map interface, Classtoinstacemap provides the method T getinstance (class<t>) and T putinstance (CLASS&LT;T&GT; t), eliminating forced type conversions. The class has a simple type of argument, often called B, that represents the upper bound of the map control, for example:
classtoinstancemap<number> numberdefaults = Mutableclasstoinstancemap.create ();
Numberdefaults.putinstance (Integer.class, integer.valueof (0));
Technically speaking,classtoinstancemap<b>Realized themap<class< extends B>, b> or, this is a mapping from a subclass of B to a B object, which may makeClasstoinstancemap's generics are mildly chaotic, but just remember that B is always the upper bound type of map, usually B is just an object. Guava provides useful implementations, MUTABLECLASSTOINSTANCEMAP and Immutableclasstoinstancemap. Focus: Like the other map<class,object>ClasstoinstancemapContains the native type of the project, a native type and his corresponding wrapper class can be mapped to different values;

private static void TestClass () {
Classtoinstancemap<person> Classtoinstancemap =mutableclasstoinstancemap.create ();

Person person= New Person (1,20, "abc", "46464", 1,100);

Classtoinstancemap.putinstance (Person.class,person);


System.out.println ("String:" +classtoinstancemap.getinstance (String.class));
System.out.println ("integer:" + classtoinstancemap.getinstance (integer.class));

Person Person1=classtoinstancemap.getinstance (Person.class);

}

3.4 Predicates and filters

The predicate (predicate) is used to filter the collection;

The predicate is a simple interface, only one method returns a Boolean value, but he is a very surprising collection method, and when you combine the Collections2.filter method, this filtering method returns the original set of elements that satisfy the predicate interface;

For example: Filter out women in a set

public static void Main (string[] args)
{
Optional<immutablemultiset<person>> optional=optional.fromnullable (TestPredict ());

if (Optional.ispresent ())
{
for (person P:optional.get ())
{
System.out.println ("Woman:" +p);
}
}

System.out.println (Optional.ispresent ());
}


public static immutablemultiset<person> Testpredict ()
{
List<person> personlist=lists.newarraylist (New person (1, 1, "a", "46546", 1, 20),
New Person (2, 1, "AB", "46546", 0, 30),
New Person (3, 1, "abc", "46546", 0, 25),
New Person (4, 1, "AEF", "46546", 1, 50),
New Person (5, 1, "Ade", "46546", 0, 27),
New Person (6, 1, "ACC", "46546", 1, 29),
New Person (7, 1, "Add", "46546", 0, 33));

Return immutablemultiset.copyof (Collections2.filter (personlist,new predicate<person> () {
@Override
Public boolean apply (person input) {
Return Input.getsex () ==0;
}
}));
}

Predicates contains some built-in filtering methods, such as in, and, not, etc., according to the actual situation to choose to use.

3.5 Functions and conversions

Convert a set for another set;

Examples are as follows:

public static void Main (string[] args)
{
Optional<immutablemultiset<string>> optional=optional.fromnullable (TestTransform ());

if (Optional.ispresent ())
{
For (String P:optional.get ())
{
System.out.println ("Name:" +p);
}
}

System.out.println (Optional.ispresent ());
}


public static immutablemultiset<string> Testtransform ()
{
List<person> personlist=lists.newarraylist (New person (1, 1, "a", "46546", 1, 20),
New Person (2, 1, "AB", "46546", 0, 30),
New Person (3, 1, "abc", "46546", 0, 25),
New Person (4, 1, "AEF", "46546", 1, 50),
New Person (5, 1, "Ade", "46546", 0, 27),
New Person (6, 1, "ACC", "46546", 1, 29),
New Person (7, 1, "Add", "46546", 0, 33));

Return immutablemultiset.copyof (Lists.transform (personlist,new Function<person, string> () {
@Override
Public String apply (person input) {
return Input.getname ();
}
}));
}

3.6 Sort

Is guava a very flexible comparison class that can be used to manipulate, extend, and treat as comparators, sorting provides a lot of control over the set sort;

Examples are as follows:

Lists.newarraylist (30, 20, 60, 80, 10);

Ordering.natural (). sortedcopy (numbers); 10,20,30,60,80

Ordering.natural (). Reverse (). Sortedcopy (numbers); 80,60,30,20,10

Ordering.natural (). min (numbers); 10

Ordering.natural (). Max (numbers); 80

Lists.newarraylist (+, 10);

Ordering.natural (). Nullslast (). sortedcopy (numbers); Ten, 20,30,60,80,null

Ordering.natural (). Nullsfirst (). sortedcopy (numbers); null,10,20,30,60,80

public static void Testordering ()
{
List<person> Personlist=lists.newarraylist (
New Person (3, 1, "abc", "46546", 0, 25),
New Person (2, 1, "AB", "46546", 0, 30),
New Person (5, 1, "Ade", "46546", 0, 27),
New Person (1, 1, "a", "46546", 1, 20),
New Person (6, 1, "ACC", "46546", 1, 29),
New Person (4, 1, "AEF", "46546", 1, 50),
New Person (7, 1, "Add", "46546", 0, 33)
);

Ordering<person> byage=new ordering<person> () {
@Override
public int compare (person left, person right) {
Return Right.getage ()-left.getage ();
}
};

for (person p:byage.immutablesortedcopy (personlist))
{
SYSTEM.OUT.PRINTLN (P);
}
}

Guava in the combined portion of the API usage record finished, hope to the majority of the cock wire helpful.

"Turn" EVA (Guava) API quickly familiar with the use of

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.