Basic for stream [Java]


Stream is a convenient API which is introduced in Java 8 for aggregating values of aggregates such as arrays and collections.

In this article, I would like to introduce basic knowledge of Stream.

­čŚ╗ Count of collection´╝Ücount

count() method in stream API counts the elements in stream object.

articles.stream().filter(i -> i.isDraft()).count() //=> n

­čĹŻ noneMatch

noneMatch() method is a method which takes argument as a Predicate and if none of element of stream matches the given Predicate, then it returns true otherwise false.

articles.stream().noneMatch(i -> i.isDraft())
articles.stream().noneMatch(ArticleForm::isDraft)

­čś╝ Stream Optional Value

java.util.Optional<T> class is a wrapper for a non-null value that may or may not contain a non-null value.

final Optional<Article> article = Articles.stream()
.filter(a -> a.getId() == 1)
.findFirst();

To get and use the value from Optional, write it as follows:

article.ifPresent(value -> System.out.println("Article.id is" + article.getId()));
formOpt.ifPresent(article -> {
article.setTitle("hoge");
article.setContent("fuga");
});

ifPresent(Consumer<? super T> action) method from the Optional class takes an action on the value contained in Optional object.

­čÉ× Special Thanks

­čľą Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!