Use stream instead of loop scheme
1. Define a article class including title, author, label
1 Private classArticle {2 3 Private FinalString title;4 Private FinalString author;5 Private FinalList<string>tags;6 7 PrivateArticle (string title, string author, list<string>tags) {8 This. title =title;9 This. Author =author;Ten This. tags =tags; One } A - PublicString GetTitle () { - returntitle; the } - - PublicString Getauthor () { - returnauthor; + } - + PublicList<string>getTags () { A returntags; at } -}
Case one, find the first article labeled "Java"
(1) Traditional methods
Public article Getfirstjavaarticle () {for (article article:articles) { if (Article.gettags (). Contains ("Java" ) { return article; } } return null;}
(2) Use stream to complete the above functions
Public optional<article> getfirstjavaarticle () { return Articles.stream () . Filter (Article- Article.gettags (). Contains ("Java")) . FindFirst (); }
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.
Case two, get all the tags that contain "Java" articles
(1) Traditional methods
Public list<article> Getalljavaarticles () { list<article> result = new arraylist<> (); for (article article:articles) { if (Article.gettags (). Contains ("Java")) { result.add (article); } } return result;}
(2) Use stream to complete the above functions
Public list<article> Getalljavaarticles () { return Articles.stream () . Filter (Article- Article.gettags (). Contains ("Java")) . Collect (Collectors.tolist ());
Case three, according to the author to group all the articles.
(1) Traditional methods
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;}
(2) Use stream
Public map<string, List<article>> Groupbyauthor () { return Articles.stream () . Collect ( Collectors.groupingby (Article::getauthor));}
Case four, find all the different labels in the collection
(1) Traditional methods
Public set<string> Getdistincttags () { set<string> result = new hashset<> (); for (article article:articles) { Result.addall (article.gettags ()); } return result;}
(2) using stream for
Public set<string> Getdistincttags () { return Articles.stream () . FLATMAP (Article-Article.gettags (). Stream ()) . Collect (Collectors.toset ());}
Stream's API link.
Java 8 Stream uses