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.

🗽 filter

filter() returns some elements of this stream that match the given predicate.

List<String> sampleList = Arrays.asList("a1", "a2", "b1", "c2", "c1");
sampleList
.stream()
.filter(s -> s.startsWith("a"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println); // => A1 A2

🏈 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)

🐞 Instream.range

Instream.range(int startInclusive, int endExclusive) returns a sequential ordered stream elements from startInclusive(inclusive) to endExclusive(exclusive) by an incremental step of 1.

IntStream.range(1, 4).forEach(System.out::println);
// => 1, 2, 3

🤔 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.

🎉 Add original validation

In this section, I would like to introduce how to add an original validation.

Annotation class

Initially, please create an annotation class:

package com.example.validation;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Documented
@Constraint(validatedBy = {ArticleTitleValidator.class})
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface ArticleTitle {
String message() default "{com.example.validation.ArticleTitle.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

Validation class

Please add validation class:

package com.example.validation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
@Component
public class ArticleTitleValidator implements ConstraintValidator<ArticleTitle, String> {
@Autowired
ArticleService service;
@Override
public void initialize(ArticleTitle constraint) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (StringUtils.isEmpty(value)) {
return true;
}
return service.findByTitle(value) == null;
}
}

Set validation message

Please define a validation message in Unicode. native2ascii command can convert UTF-8 to Unicode or ASCII.

native2ascii
# Input any words or file path which should be converted

You should add a converted sentence to ValidationMessages.properties:

com.example.validation.ArticleTitle.message=\u30bf\u30a4\u30c8\u30eb\u306f\u30e6\u30cb\u30fc\u30af\u306b\u3057\u3066\u304f\u3060\u3055\u3044

Apply validator

You can apply your original validator to your code:

package com.example.validation;
class Article {
@ArticleTitle
private String title;
}

🏀 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!!