java 8 stream使用

來源:互聯網
上載者:User

標籤:nal   tle   add   api   ring   html   tags   延遲   blog   

使用stream代替迴圈的方案

1、定義一個Article類包括標題、作者、標籤

 1 private class Article { 2   3         private final String title; 4         private final String author; 5         private final List<String> tags; 6   7         private Article(String title, String author, List<String> tags) { 8             this.title = title; 9             this.author = author;10             this.tags = tags;11         }12  13         public String getTitle() {14             return title;15         }16  17         public String getAuthor() {18             return author;19         }20  21         public List<String> getTags() {22             return tags;23         }24     }

案例一、找出標籤為“java”的第一篇文章

(1)傳統方法

public Article getFirstJavaArticle() {     for (Article article : articles) {        if (article.getTags().contains("Java")) {            return article;        }    }     return null;}

 (2)使用stream完成上述功能

public Optional<Article> getFirstJavaArticle() {      return articles.stream()        .filter(article -> article.getTags().contains("Java"))        .findFirst();    }

  我們首先使用 filter 操作去找到所有包含Java標籤的文章,然後使用 findFirst() 操作去擷取第一次出現的文章。因為Stream是“延遲計算”(lazy)的並且filter返回一個流對象,所以這個方法僅在找到第一個匹配元素時才會處理元素。

案例二、擷取所有標籤包含“java”的文章

 (1)傳統方法

 

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

 

(2)使用stream完成上述功能

public List<Article> getAllJavaArticles() {      return articles.stream()        .filter(article -> article.getTags().contains("Java"))        .collect(Collectors.toList());    }

  案例三、根據作者來把所有的文章分組。

(1)傳統方法

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)使用stream

public Map<String, List<Article>> groupByAuthor() {      return articles.stream()        .collect(Collectors.groupingBy(Article::getAuthor));}

 案例四、尋找集合中所有不同的標籤

(1)傳統方法

public Set<String> getDistinctTags() {     Set<String> result = new HashSet<>();     for (Article article : articles) {        result.addAll(article.getTags());    }     return result;}

(2)使用stream實現

public Set<String> getDistinctTags() {      return articles.stream()        .flatMap(article -> article.getTags().stream())        .collect(Collectors.toSet());}

  stream的api連結。

 

java 8 stream使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.