Oracle began formally introducing lambda expressions in Java8, although it was a bit late, but as a Java developer we were excited. Before we get into formal learning, we now experience the magic of lambda.
We quote a wonderful translation from Importnew: Java8: Don't use loops as an experiential project.
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
This time we will take the article as an example. An article has a title, an author and several tags.
ImportJava.util.List; Public class article { Private FinalString title;Private FinalString author;Private FinalList<string> tags; Public article(string title, string author, list<string> tags) { This. title = title; This. Author = author; This. tags = tags; } PublicStringGetTitle() {returnTitle } PublicStringGetauthor() {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.
publicgetFirstJavaArticle() { for (Article article : articles) { if (article.getTags().contains("Java")) { return article; } } returnnull;}
Now we use the stream API to work around this problem.
public Optional<Article> getFirstJavaArticle() { return articles.stream() .filter(article -> 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.
Note: The call to the filter method creates a formula for a new collection, but does not force execution, but delays execution, after which the call to the count () method executes, and this method of count is called eager.
The distinction between eager and lazy is simple, look at their return, if the stream is returned then the method is lazy, otherwise eager. This distinction is very meaningful, and the usual usage is a string of lazy methods followed by a eager method to produce the result.
Now, let's get all the matching elements instead of just getting the first one.
Use the For Loop scheme first.
publicgetAllJavaArticles() { new 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> getAllJavaArticle() { return articles.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.
Public Map<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?
publicMap<StringList<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.
publicSet<String> getDistinctTags() { Set<Stringnew 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.
Set<String> getDistinctTags() { return articles.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.
Note : in the following article we will specifically describe the magical features of Flatmap, unlike Map,foreach these methods, flatmap the realization of the flow of the transformation.
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.
I have almost completely quoted the author's complete translation, just a few notes in some places to explain, in order to facilitate the understanding of grammatical points, because the translation as a Lambda experience project is very appropriate.
Original link: deadcoderising translation: Importnew.com-Jin Lin
Link: http://www.importnew.com/14841.html
Java8 Learning (1)-Lambda experience Zone