Java8新特性:使用Stream优化对集合的操作(Demo)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29229567/article/details/83900155

Java8新特性:使用Stream优化对集合的操作(Demo)

以文章类为例子,进行【集合】操作。一篇文章拥有一个标题,一个作者和几个标签。

private class Article {
    private final String title;
    private final String author;
    private final List tags;

    private Article(String title, String author, List tags) {
        this.title = title;
        this.author = author;
        this.tags = tags;
    }

    public String getTitle() {
        return title;
    }
    public String getAuthor() {
        return author;
    }
    public List getTags() {
        return tags;
    }
}

例子1:在集合中查找包含“Java”标签的第一篇文章。
      A.使用for循环的解决方案。

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

      B.使用Stream API的解决方案。

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

例子2:在集合中查找包含“Java”标签的所有文章。
      A.使用for循环的解决方案。

public List getAllJavaArticles() {
    List result = new ArrayList<>();

    for (Article article : articles) {
        if (article.getTags().contains("Java")) {
            result.add(article);
        }
    }

    return result;
}

      B.使用Stream API的解决方案。

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

例子3:根据作者把所有文章分类。
A.使用for循环的解决方案。

public Map> groupByAuthor() {
    Map> result = new HashMap<>();

    for (Article article : articles) {
        if (result.containsKey(article.getAuthor())) {
            result.get(article.getAuthor()).add(article);
        } else {
            ArrayList articles = new ArrayList<>();
                articles.add(article);
            result.put(article.getAuthor(), articles);
        }
    }

    return result;
}

      B.使用Stream API的解决方案

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

例子4:查找集合中所有不同的标签。
      A.使用for循环的解决方案。

public Set getDistinctTags() {
    Set result = new HashSet<>();

    for (Article article : articles) {
        result.addAll(article.getTags());
    }

    return result;
}

      B.使用Stream API的解决方案。

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

猜你喜欢

转载自blog.csdn.net/qq_29229567/article/details/83900155