[Go] basic guava tool

Source: Internet
Author: User

Transferred from: Http://www.cnblogs.com/renchunxiao/p/3661918.html?utm_source=tuicool using the Joiner classConnecting any string with a delimiter is something that most programmers often do. They often use array,list,iterable and the loop variable adds each temporary variable to the StringBuilder and adds a separator between them. These cumbersome handling methods are as follows:
Public String buildstring (list<string> stringlist, String delimiter) {StringBuilder builder = new StringBuilder ();    for (String s:stringlist) {if (s!=null) {builder.append (s). Append (delimiter);  }} builder.setlength (Builder.length () –delimiter.length ()); return builder.tostring ();}

Note the delimiter to remove on the last side. It's not hard to understand, but using the Joiner class gives you a simple code template. The same example uses the Joiner class code as follows:

Public String buildstring (list<string> stringlist, String delimiter) {        return  Joiner.on (delimiter). Skipnulls (). Join (stringlist);}

 This is more concise and does not make mistakes. If you want to replace the null value, you can use the following method:

Joiner.on ("|"). Usefornull ("No value"). Join (Stringlist);

There are a few things to note about using the Joiner class. The Joiner class can handle not only the array, list, and iterable of strings, but also the array, list, iterable of any object. The result is a ToString () method that invokes each element. Therefore, if you do not use Skipnulls or usefornull, a null pointer exception is thrown. Once the joiner objects are created immutable, they are thread-safe and can be viewed as solid. Then take a look at the following code snippet:

Joiner Stringjoiner = Joiner.on ("|").  Skipnulls ();  Using the Usefornull method will return a new joiner instance Stringjoiner.usefornull ("Missing"); Stringjoiner.join ("foo", "bar", null);

In the above code example, the Usefornull method does not work, and the null value is still reported to the NPE.

Joiner can not only return strings, but also work with StringBuilder:
StringBuilder StringBuilder = new StringBuilder (); Joiner Joiner = Joiner.on ("|"). Skipnulls ();//The StringBuilder instance that is returned contains the string joiner.appendto (StringBuilder, "foo", "Bar", "Baz") of the connection completion;

In the example above, we pass in a StringBuilder parameter and return a StringBuilder instance.

The Joiner class can also use classes that implement the Appendable interface.
FileWriter FileWriter = new FileWriter (new File ("path")):list<date> datelist = GetDates (); Joiner Joiner = Joiner.on ("#"). Usefornulls ("");//Returns the FileWriter instance Joiner.appendto (filewriter,datelist) after concatenation of strings;

This is a similar example to the previous one. When we pass in a FileWriter instance and a set of data, we will splice the set of data and append it to the FileWriter and return it.

As we can see, joiner makes some of the public operations very simple. There is a special way to implement the Mapjoiner method, and the Mapjoiner method uses a delimiter like joiner to separate each set of keys from value, and there is a separator between key and value. The Mapjoiner method is created as follows:
Mapjoiner Mapjoiner = Joiner.on ("#"). Withkeyvalueseparator ("=");

Take a quick look at what's above:

    • The Joiner.on ("#") method creates an instance of the Joiner.
    • Calling the Withkeyvalueseparator method with the returned joiner instance will return the Mapjoiner object.
The following is the unit test code for the Mapjoiner method:
@Testpublic void Testmapjoiner () {String expectedstring = "Washington d.c=redskins#new York City=giants#philadelphia=ea   Gles#dallas=cowboys ";  Map<string,string> TestMap = Maps.newlinkedhashmap ();  Testmap.put ("Washington D.C", "Redskins");  Testmap.put ("New York City", "Giants");  Testmap.put ("Philadelphia", "Eagles");  Testmap.put ("Dallas", "cowboys"); String returnedstring = Joiner.on ("#").   Withkeyvalueseparator ("="). Join (TESTMAP); Assertthat (Returnedstring,is (expectedstring));}

Review time

At the beginning of the unit test, creating a key and value are all Linkedhashmap instances of the string, and it's worth noting that we use the static Factory method Newlinkedhashmap () to create the maps class in Com.google.common. Collect bag. Then use the Joiner class to create a string that uses key to stitch with value. Finally we assert whether he is the same as the string we expect to return. using the Splitter classAnother problem that programmers often deal with is splitting a string with a specific delimiter and getting an array of strings. If you need to read a text file, you will always do something like that. But the String.Split method is not perfect, see the following example:
String teststring = "Monday,tuesday,,thursday,friday,";//parts is [Monday, Tuesday,, thursday,friday]string[] parts = t Eststring.split (",");

As you can see, the String.Split method omits the last 2 empty strings. In some cases, this is what you need, but it is up to the programmer to decide whether or not to omit it. The splitter class can help us achieve the opposite function of the joiner class. Splitter can use a single character, a fixed string, a regular expression string, a regular expression object, or a Charmatcher object (another guava class, described in this chapter) to split a string. You can create a splitter object and then use it given a specific delimiter. Once you have a splitter instance, you can call the Split method and return an iterator object that contains the split string.

Splitter.on (' | '). Split ("Foo|bar|baz"); Splitter Splitter = Splitter.on ("\\d+");

In the example above, we see a splitter instance using the ' | ' Character segmentation, and another instance using regular expressions for segmentation.

Splitter there is a way to handle the preceding and trailing spaces is trimresults.
Splits on ' | ' and removes any leading or trailing whitespacesplitter splitter = Splitter.on (' | '). Trimresults ();

Like the Joiner class, the Splitter class is also an immutable class, so you should use the splitter instance returned after calling the Trimresults method when you use it.

Splitter Splitter = Splitter.on (' | '); /next call returns a new instance, does notmodify the Original!splitter.trimresults ();//result would still contain empty E lementsiterable<string> parts = Splitter.split ("1|2|3| | |");

The Splitter class, like Joiner and Mapjoiner, also has a mapsplitter class. The Mapsplitter class can convert a string to a map instance, and the order of the elements is the same as the string given. Use the following method to construct a Mapsplitter instance:

Mapsplitter is defined as an inner class of splittersplitter.mapsplitter Mapsplitter = Splitter.on ("#"). Withkeyvalueseparator ("=");
You can see that Mapsplitter is created in the same way as Mapjoiner. First, specify a delimiter for splitter, and then specify the delimiter for the Mapsplitter object key and value. Here is an example of Mapsplitter, which implements the opposite function with Mapjoiner.
@Testpublic void Testsplitter () {String startstring = "Washington d.c=redskins#new York city=giants#philadelphia=eagles   #Dallas =cowboys ";  Map<string,string> TestMap = Maps.newlinkedhashmap ();  Testmap.put ("Washington D.C", "Redskins");  Testmap.put ("New York City", "Giants");  Testmap.put ("Philadelphia", "Eagles");  Testmap.put ("Dallas", "cowboys");   Splitter.mapsplitter Mapsplitter = Splitter.on ("#"). Withkeyvalueseparator ("=");   map<string,string> Splitmap = Mapsplitter.split (startsring); Assertthat (Testmap,is (Splitmap));}  
Review TimeThe unit test above is to divide a string into an instance of Linkedhashmap with Mapsplitter. Then assert whether the returned Linkedhashmap instance is the same as we expect to be a linkedhashmap instance. The two classes of joiners and splitters should be tools for every Java developer. manipulating strings using guavaWhatever language you like, all string-related things are tedious and error-prone. Sometimes we need to read the data from a file or data and reformat the data for submission to the user, or save the data in a fixed format. Fortunately, guava provides us with a very useful class that makes it easier to manipulate strings. These classes are as follows:
    • Charmatcher
    • Charsets
    • Strings
Now let's take a look at how to use them in your code. In the first example, this unit test will show the use of the ASCII class method to determine whether a character is lowercase. The second example shows the conversion of lowercase strings to uppercase. using the Charsets classIn Java, there are 6 standard character sets that are supported on every Java platform. This is related to the frequent running of the following code:
byte[] bytes = Somestring.getbytes ();
But there is a question about the above code. Without specifying the character set you want to return bytes to, you will get the system to use the runtime default character set to return the bytes, which may cause problems with the default character set that is not what you want. So the best thing to do is like this:
try{bytes = "Foobarbaz". GetBytes ("UTF-8");} catch (Unsupportedencodingexception e) {//this really can ' t happen UTF-8 must be supported}
But there are still two problems in the code above:
    • UTF-8 is bound to be supported on the Java platform, so unsupportedencodingexception must not be thrown
    • Once we use a string to specify the definition of a character set, we can generate a spelling error and then cause an exception to be thrown.
The Charsets class can help us, and the Charsets class provides the set of characters supported by the static final six Java platforms. Using the Charsets class we can make the above example simpler:
byte[] Bytes2 = "Foobarbaz". GetBytes (Charsets.utf_8);
It is noteworthy that in JAVA7, Standardcharsets also provides the same functionality. Now let's look at the strings class. using the Strings classThe strings class provides some handy and practical ways to handle strings. Have you ever written a code like the following:
StringBuilder builder = new StringBuilder ("foo");  char c = ' x ';  for (int i=0; i<3; i++) {builder.append (c); }return builder.tostring ();
The 6 lines of code in the above example can be replaced with one line of code.
Strings.padend ("foo", 6, ' X ');
The second parameter is important, and 6 specifies that the minimum length of the returned string is 6, rather than specifying how many times the ' x ' character is appended after the string. If the supplied string length is already greater than 6, no append is made. There is also a similar Padstart method that appends a character to the specified length before the given string. There are three very useful ways to handle null values in the strings class:
    • Nulltoempty: This method accepts a string parameter, if the passed parameter is not a null value, or if the length is greater than 0, returns the empty string ("");
    • Emptytonull: This method is similar to Nulltoempty, which returns a null value if the passed argument is an empty string or null.
    • IsNullOrEmpty: This method checks whether the incoming parameter is null and length, and returns True if it is null and the length is 0.
Perhaps, it would be a good idea to always handle incoming string arguments in any way using the Nulltoempty method. using the Charmatcher classCharmatcher provides the ability to match a specific string in a certain string. The methods in the Charmatcher class can also make formatting easier. For example, you can format a multiline string into a single line, and the newline character will be replaced with a space.
CharMatcher.BREAKING_WHITESPACE.replaceFrom (Stringwithlinebreaks, ");
There is also a version of Replacefrom, which requires a charsequence value as the 2nd parameter value instead of a single character. Remove multiple spaces and tabs in place of a single space, with the following code:
@Testpublic void Testremovewhitespace () {String tabsandspaces = "string with spaces and         tabs";  String expected = "string with spaces and tabs";  String scrubbed = CharMatcher.WHITESPACE.collapseFrom (tabsandspaces, "); Assertthat (Scrubbed,is (expected));}
In the test code above, we replaced all the spaces and tabs with a single space, all on one line. The above example works in some cases, but what if the string has a space at the beginning and we want to remove it? The returned string will still contain spaces in front of it, so you can use the Trimandcollapsefrom method:
@Testpublic void Testtrimremovewhitespace () {String tabsandspaces = "   string with spaces and       tabs";  String expected = "string with spaces and tabs"; String scrubbed = charmatcher.whitespace.   Trimandcollapsefrom (Tabsandspaces, "); Assertthat (Scrubbed,is (expected));}
In this test, we will once again replace multiple spaces and tabs with a single space on one line. It is impractical to list all the methods available in the Charmatcher class, here is not the place to replace a set of matched characters, we reserve the example of the matched characters:
@Test public    void Retainfromtest ()    {        String lettersandnumbers = "foo989yxbar234";        String expected = "989234";        String actual = CharMatcher.JAVA_DIGIT.retainFrom (lettersandnumbers);        Assertequals (expected, actual);    }
In this example we find the numbers in the "foo989yxbar234" string and keep them. Before we go down, we should look at the powerful features in the last Charmatcher class. You can combine multiple Charmatcher class instances to create a new Charmatcher class instance. Suppose you need to create an instance of a Charmatcher class that matches numbers and spaces:
Charmatcher cm = CharMatcher.JAVA_DIGIT.or (charmatcher.whitespace);
It will now match any number or space. The Charmatcher class is powerful and useful for manipulating strings. using the Preconditions classThe preconditions class is a collection of static methods used to validate the state of our code. Preconditions is very important because they guarantee that the code we expect to execute successfully is met. If the conditions are different from what we expected, we will promptly respond to the questions. As before, the importance of using prerequisites is to ensure that our code behaves and is useful in debugging. You can write your own prerequisites, like this:
if (someobj = = null) {    throw new IllegalArgumentException ("Someobj must not is null");}
Using the method in preconditions (requires static import), it is easy to check an empty value.
Checknotnull (Someobj, "someobj must not being null");
Next, we will show examples of using prerequisites:
public class Preconditionexample {private String label;  Private int[] values = new INT[5];  private int currentindex;  Public Preconditionexample (String label) {//returns label if NOT null This.label = checknotnull (label, "label can ' t be null"); } public void Updatecurrentindexvalue (int index, int valuetoset) {//Check whether the index is valid This.currentindex = Checkelementindex     (Index, Values.length, "index out of Bounds for values");     Check the parameter value checkargument (Valuetoset <=, "value can ' t be more than 100");  Values[this.currentindex] = Valuetoset;  } public void Dooperation () {CheckState (Validateobjectstate (), "Can ' t perform operation");    Private Boolean validateobjectstate () {return this.label.equalsIgnoreCase ("open") && values[this.  currentindex]==10; }}
Here is a summary of the four methods in the above example:
    • Checknotnull (T object, Object message): This method returns if object is not NULL, and if NULL throws a null pointer exception.
    • Checkelementindex (int index, int size, Object message): In this method, index is the subscript of the element you are going to access, and the size is the length of the array,list or string to be accessed. Then the checksum is valid if invalid throws Indexoutofboundsexception.
    • Checkargument (boolean expression, Object message): This method passes in the Boolean expressions. This Boolean expression, if true, continues execution, otherwise throws illegalargumentexception.
    • CheckState (Boolean expression, Object message): This method passes in a Boolean expression that involves the state of the object, not the parameter. This Boolean expression, if true, continues execution, otherwise throws illegalargumentexception.
Object ToolIn this section we will cover practical ways to help you check for null values and create methods for ToString and Hashcode. Let's take a look at a useful class that implements the comparable interface. Getting help with the toString methodThe ToString method must be rewritten when we are debugging, and it's tedious to rewrite it. However, the objects class can use the Tostringhelper method to make rewriting easier. Look at the following example:
public class book implements comparable<book> {private person author;  Private String title;  Private String publisher;  Private String ISBN;  private double price; Public String toString () {return objects.tostringhelper (this). Omitnullvalues (). Add ("title", title). Add ("Author",  Author). Add (publisher, publisher). Add ("Price", "price"). Add ("ISBN", ISBN). toString (); }}
Let's look at the ToString method:
    • First we pass in a book object to create a Objects.tostringhelper instance.
    • In the second step, we call omitnullvalues to exclude any null value properties.
    • Call the Add method to add tags and properties for each property.
Check for null valueThe Firstnonnull method takes 2 parameters and returns the first argument if it is not null.
String value = Objects.firstnonnull (somestring, "Default value");
Firstnonnull method Use time if you are not sure if the value passed in is NULL, you can provide a default value to it. Note: If the 2 arguments passed in are null, a null pointer exception is thrown. Create Hash CodesWriting hashcode methods for classes is basic but boring. The objects class can help us to use the Hashcode method more easily. Consider the book class with 4 attributes: Title, author, publisher, and ISBN. The following code shows the use of the Object.hashcode method to return the Hashcode value.
public int hashcode () {return Objects.hashcode (title, author, publisher, ISBN);}
implementing the CompareTo methodUsing the book class again, here is a typical implementation of the CompareTo method.public int compareTo (book o) {
int result = This.title.compareTo (O.gettitle ());  if (Result! = 0) {return result;  } result = This.author.compareTo (O.getauthor ());  if (Result! = 0) {return result;  } result = This.publisher.compareTo (O.getpublisher ());  if (Result!=0) {return result; } return This.isbn.compareTo (O.GETISBN ());}
Now let's take a look at using the Comparisonchain class to implement the CompareTo method:
public int compareTo (book o) {return Comparisonchain.start (). Compare (This.title, O.gettitle ()). Compare (This.author, O . Getauthor ()). Compare (This.publisher, O.getpublisher ()). Compare (THIS.ISBN, O.GETISBN ()). Compare (This.price, O.get Price ()). result (); }
The second example looks more compact and better read. Moreover, the Comparisonchain class will be in the first comparison if the return non-zero stop comparison, only one case returns 0, that is, all the comparison returned is 0. OverviewIn this chapter we describe many of the underlying operations. We learned how to use guava to make it easier to split strings by using Joiner, Splitter, and very useful mapjoiner and Mapsplitter classes. We also learned to manipulate strings using charsets, Charmatcher, and Strings. We learned how to make our code stronger and easier to debug by using the preconditions class. In the objects class, we learned to use methods to set default values and create ToString and Hashcode methods. We also learned that using the Comparisonchain class to implement the CompareTo method is simpler. In the next chapter, we learn how to use guava for functional programming, which makes our programming more efficient through function and predicate interfaces.

[Go] basic guava tool

Related Article

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.