Java8 lambda expression description-write to Guava user

Source: Internet
Author: User
Tags java anonymous class

Guava

Guava is a utility repository for Google's Open source, which has been enhanced in many ways by the Java class Library. For example, support for functional programming , new collection Classes (Multimap, etc.),Cache support, and so on. Before Java8 , the relationship between guava and Java can be expressed as the following image:


But with the release of Java8, there have been some changes in the relationship between guava and Java. Many of the features provided by guava are built into the Java8, as shown in:

This article gives a few examples of how the guava can be implemented using JAVA7 or JAVA8, using code to illustrate the functionality that was originally needed.

Joiner

Joiner is used to stitch n strings, here is an example:

    @Test public    void Joinerguava () {        list<string> strlist = arrays.aslist ("One", "one", "one", "three", null);        String csv = Joiner.on (",")                . Skipnulls ()                . Join (strlist);        Assertequals ("One,two,three", CSV);    }
In Java8, we can use lambda expressions to do the same thing:

    @Test public    void JoinerJava8 () {        list<string> strlist = arrays.aslist ("One", "one", "one", "three", null);        String csv = Strlist.stream ()                . Filter (Objects::nonnull)                . Collect (Collectors.joining (","));        Assertequals ("One,two,three", CSV);    }

Ordering

Guava provides the ordering class to facilitate our creation of comparator, here's a sample code:

    Class Player {                private String name;                Public String GetName () {            return name;        }            }
    public void Orderingguava () {        //Public abstract class Ordering<t> implements Comparator<t>        ordering<player> ordering = Ordering.natural (). Nullsfirst (). Onresultof (New Function<player, String> () {            @Override public            String apply (Player foo) {                return foo.getname ();            }        });    }
In Java8, we can do this:

    public void ComparingJava8 () {        comparator<player> cmp = comparator.comparing (Player::getname,                Comparator.nullsfirst (Comparator.naturalorder ()));    }

Optional

Optional can explicitly indicate that a reference may be null, as the following is an example of a copy from the Guava document:

guavaoptional<integer> possible = Optional.of (5);p ossible.ispresent (); Returns Truepossible.get (); Returns 5
Use java.util.OptionalCan do similar things, and the method is the same, there is no code.

Preconditions.checknotnull ()

If you want to ensure that a reference is not null (throw nullpointerexceptionas soon as possible), you can write as follows:

    Class Player {                private final String name;                Public Player (String name) {            this.name = preconditions.checknotnull (name);        }            }

There are three versions of the Checknotnull () method:

public static <T> T-checknotnull (t Reference) public static <T> T Checknotnull (t reference, Object errormessage public static <T> T Checknotnull (t Reference, String errormessagetemplate, Object ... errormessageargs)
Java.util.Objects provides three similar methods:

public static <T> t Requirenonnull (t obj)//@since 1.7public static <T> t requirenonnull (t obj, String messag e)//@since 1.7public static <T> t requirenonnull (t obj, supplier<string> messagesupplier)//@since 1.8

Guava Objects

Some of the methods in the Com.google.common.base.Objects class can be replaced by java.util.Objects methods, such as:

Com.google.common.base.Objectspublic Static Boolean equal (@Nullable object A, @Nullable object B) public static int hash Code (@Nullable Object ... objects)
You can replace it with the following method:

Java.util.Objectspublic static Boolean Equals (object A, object B)//@since 1.7public static int Hashcode (object o)// @since 1.7public static int hash (Object ... values)//@since 1.7

Function-Type programming

The direct reason why many people use guava may be that they want to do functional programming better. To support functional programming, guava provides the following two interfaces:

Public interface Function<f, t> {    @Nullable T apply (@Nullable F input);} Public interface Predicate<t> {    Boolean apply (@Nullable T input);}

Guava's various collection helper classes provide a number of ways to use the above two interfaces, such as Iterables, COLLECTIONS2, maps, and so on. But guava's functional programming, which is still based on the syntax of the Java anonymous class, has somewhat reduced the ugliness of the code, but is still not ideal. The appearance of JAVA8, completely let the function of guava programming becomes superfluous.

Hashmultimap

Suppose we want to follow the player's groupid to group players, Java8 previously, you can do this:

    public void MapListJava7 (list<player> players) {        Map<integer, list<player>> groups = new hashmap& Lt;> ();        for (Player player:players) {            list<player> group = Groups.get (Player.getgroupid ());            if (group = = null) {                group = new Arraylist<> ();                Groups.put (Player.getgroupid (), group);            }            Group.add (player);        }    }
If you use Guava's Multimap, the code will be much clearer:

    public void Guavamultimap (list<player> players) {        Multimap<integer, player> groups = Arraylistmultimap.create ();        for (player player:players) {            groups.put (Player.getgroupid (), Player);        }    }
Now, you can use lambda expressions to express your intentions more clearly:

    public void GroupingByJava8 (list<player> players) {        Map<integer, list<player>> groups = Players.stream ()                . Collect (Collectors.groupingby (player::getgroupid));    }

Conclusion

Guava is a good library, but as Java itself improves, many of the features of guava have become redundant.




Java8 lambda expression description-write to Guava user

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.