Java 8: Looping a collection with a stream

Source: Internet
Author: User
Tags stream api

This paper is translated from Importnew-deadcoderising. Welcome to join the translation team. Reproduced please see at the end of the request.

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.

123456789101112131415161718192021222324 private class Article {        private final String title;        private final String author;        private final List<String> tags;         private Article(String title, String author, List<String> tags) {            this.title = title;            this.author = author;            this.tags = tags;        }        public String getTitle() {            return title;        }        public String getAuthor() {            return author;        }        public List<String> getTags() {            return tags;        }    }

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.

12345678910 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.

12345 public optional<article> getfirstjavaarticle () {   &NBSP;&NBSP;&NBSP;&NBSP; return articles.stream () &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; .filter (article-Article.gettags (). Contains ( "Java "           .findfirst (); &NBSP;&NBSP;&NBSP;&NBSP;

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.

123456789101112 public List<Article> getAllJavaArticles() {    List<Article> result = new ArrayList<>();    for (Article article : articles) {        if (article.getTags().contains("Java")) {            result.add(article);        }    }    return result;}

A scenario that uses the stream operation.

12345 publicList<Article> getAllJavaArticles() {      returnarticles.stream()        .filter(article -> 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.

12345678910111213141516 public Map<String, List<Article>> groupByAuthor() {    Map<String, List<Article>> result = new HashMap<>();    for (Article article : articles) {        if (result.containsKey(article.getAuthor())) {            result.get(article.getAuthor()).add(article);        } else {            ArrayList<Article> articles = new ArrayList<>();            articles.add(article);            result.put(article.getAuthor(), articles);        }    }    return result;}

Can we find a simple solution that uses flow operations to solve this problem?

1234 publicMap<String, List<Article>> groupByAuthor() {      returnarticles.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.

12345678910 public set<string> getdistincttags () {        set<string> result = new Code class= "Java Plain" >hashset<> ();  &NBSP;&NBSP;&NBSP;&NBSP; for (article article:articles) {           result.addall (Article.gettags ()); &NBSP;&NBSP;&NBSP;&NBSP;  &NBSP;&NBSP;&NBSP;&NBSP; return result;

OK, let's take a look at how to use the stream operation to solve this problem.

12345 publicSet<String> getDistinctTags() {      returnarticles.stream()        .flatMap(article -> 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 an example of how to use more readable code instead of loops. Be sure to look at the stream API carefully, because this article only mentions some of its fur.

Update

After receiving comments from Solarfuse and Dhruvgairola, the Getdistincttags () example was updated, using the collection (set) as the return collection.

Original link: deadcoderising translation: Importnew.com-Jin Lin
Link: http://www.importnew.com/14841.html

Reprinted from Connection: http://www.importnew.com/14841.html

Java 8: Looping a collection with a stream

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.