Go Java 8: Don't use loops anymore

Source: Internet
Author: User
Tags stream api

The following content is reproduced, not tested in jdk8, whether there are bugs in the specific business scenarios or where attention needs to be tested.

------------------Split Line----------------------

As I wrote earlier, the new features in Java 8 have changed the rules of the game. It's a whole new world for Java developers, and it's time to get used to it. In this article, we will look at some of the alternatives to traditional loops. In the new features of Java 8, the best feature is to allow us to express what we want to accomplish, not how we do it. This is where the cycle is deficient. There is a price to be paid to ensure the flexibility of the cycle. Return, break, or continue will significantly change the actual performance of the loop. This forces us to not only know what kind of code we want to implement, but also how the loop works. When we introduced the stream of Java 8, we learned some practical tricks for set-up operations. Now we're going to look at how to convert these loops into more concise, more readable code.
Start coding! Well, enough talk, it's time to show some examples! This time we will take the article as an example. An article has a title, an author and several tags.
Private classArticle {Private FinalString title; Private FinalString author; Private FinalList<string>tags;
PrivateArticle (string title, string author, list<string>tags) { This. title =title; This. Author =author; This. tags =tags; } PublicString GetTitle () {returntitle; } PublicString Getauthor () {returnauthor; } PublicList<string>getTags () {returntags; } }
Each example will contain a scenario that uses a traditional loop and a scenario that uses the new Java 8 feature. In the first example, we want to find the first article in the collection that contains the "Java" tab. Take a look at the solution that uses the For loop.
 Public article getfirstjavaarticle () {    for  (article article:articles) {        if ( Article.gettags (). Contains ("Java")) {            return  article;        }    }     return NULL ;}
Now we use the stream API to work around this problem.
 Public Optional<article> getfirstjavaarticle () {      return  articles.stream ()         Article.gettags (). Contains ("Java"))        . FindFirst ();    }
Isn't it cool? We first use the filter operation to find all the articles that contain the Java tags, and then use the FindFirst () action to get the first occurrence of the article. Because stream is lazy and filter returns a Stream object, this method processes the element only when the first matching element is found. Now, let's get all the matching elements instead of just getting the first one. Use the For Loop scheme first.
 Public List<article> getalljavaarticles () {     Listnew arraylist<>();       for (article article:articles) {        if (Article.gettags (). Contains ("Java")) {            Result.add ( article);        }    }      return result;}
A scenario that uses the stream operation.
 Public List<article> getalljavaarticles () {      return  articles.stream ()         Article.gettags (). Contains ("Java"))        . Collect (Collectors.tolist ());    
In this example we use the collection operation to explicitly add a matching article to the collection by executing a small amount of code on the return stream instead of manually declaring a set merge. So far it's good. It's time to cite some of the powerful examples that highlight the stream API. Group all the articles according to the author. As usual, we use a recycling scheme.
 PublicMap<string, list<article>>Groupbyauthor () {Map<string, list<article>> result =NewHashmap<>();  for(article article:articles) {if(Result.containskey (Article.getauthor ())) {Result.get (Article.getauthor ()). Add (article); } Else{ArrayList<Article> articles =NewArraylist<>();            Articles.add (article);        Result.put (Article.getauthor (), articles); }    }     returnresult;}
Can we find a simple solution that uses flow operations to solve this problem?
 Public Map<string, list<article>> groupbyauthor () {      return  articles.stream ()        . Collect (Collectors.groupingby (Article::getauthor));}
Very good! Using the Groupingby operation and the Getauthor method, we get a cleaner, more readable code. Now we look at all the different tags in the collection. Let's start with the example of using loops.
 Public Set<string> getdistincttags () {     Setnew hashset<>();       for (article article:articles) {        Result.addall (article.gettags ());    }      return result;}
OK, let's take a look at how to use the stream operation to solve this problem.
 Public Set<string> getdistincttags () {      return  articles.stream ()          Article.gettags (). Stream ())        . Collect (Collectors.toset ());
It's awesome! Flatmap helped me turn the list of labels into a return stream, and then we used collect to create a set of co-operation for the return value. Everything is possible. The above is how to use the more readable code instead of the loop example. Be sure to look at the stream API carefully, because this article only mentions some of its fur. After updating the comments received by Solarfuse and Dhruvgairola, update the Getdistincttags () example, using the collection (set) as the return collection.

Original link: deadcoderising translation: Importnew.com-Jin Lin
Link: http://www.importnew.com/14841.html
[ Reprint please keep the source, translator and translation links.] ]

Go Java 8: Don't use loops anymore

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.