??????????????д???Java 8?е??1????????????????????Java??????????????????μ????磬??????????????????
?????????????????????????????????Щ???????????Java 8???1????????У?????????????????????????????????????????????????????????????????????????????????????????????????return??break ???? continue???????????????????????????????????????????????????????????????????????????????
?????????Java 8??????Stream???????????????Щ???????????ü??ɡ??????????????????????Щ????????????????????????
???????????
?????e????????????????????Щ???????
????????????????????????????????????????????????????????
private class Article {
private final String title;
private final String author;
private final List<String> tags;
private Article(String title?? String author?? List<String> tags) {
this.title = title;
this.author = author;
this.tags = tags;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public List<String> getTags() {
return tags;
}
}
?????????????????????????????????????????Java 8????????????
???????????????????????????в??????“Java”?????????????
????????????for?????????????
public Article getFirstJavaArticle() {
for (Article article : articles) {
if (article.getTags().contains("Java")) {
return article;
}
}
return null;
}
???????????????Stream API????????????????????
????public Optional<Article> getFirstJavaArticle() {
????return articles.stream()
????.filter(article -> article.getTags().contains("Java"))
????.findFirst();
????}
?????????????????????? filter ???????????а???Java????????£??????? findFirst() ????????????γ????????????Stream??“??????”??lazy???????filter????????????????????????????????????????????????????
????????????????????????????????????????????
???????????for?????????
public List<Article> getAllJavaArticles() {
List<Article> result = new ArrayList<>();
for (Article article : articles) {
if (article.getTags().contains("Java")) {
result.add(article);
}
}
return result;
}
???????Stream???????????
????public List<Article> getAllJavaArticles() {
????return articles.stream()
????.filter(article -> article.getTags().contains("Java"))
????.collect(Collectors.toList());
????}
?????????????????????? collection ???????????????????????????????????????????????????????????μ???????
????????????????????????Щ???Stream API???????????
???????????????????е????·??顣
????????????????????????
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;
}