使用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链接。