Trying to get a non-empty stream from a Optional stream in java was pretty tedious. I had no choice but to do my best with `filter ()` or `flatMap ()` as in https://www.baeldung.com/java-filter-stream-of-optional. However, it became much easier with the addition of Optional :: stream from java 9.
Now, suppose that there is a function that returns ```Optional.empty () `` `if it is an empty string, as shown below. Suppose you want to apply this to each element of a string list to get a list of non-empty characters.
	static Optional<String> map(String s) {
		if (s.length() == 0) {
			return Optional.empty();
		}
		return Optional.of(s);
	}
It's like this to work hard with  filter </ code>.
		List.of("1", "2", ,"", "3").stream()
			.map(Hoge::map)
			.filter(Optional::isPresent)
			.map(Optional::get)
		    .collect(Collectors.toList());
Using the java 9 Optional :: stream, this is the case.
		List.of("1", "2", "", "3").stream()
			.map(Hoge::map)
			.flatMap(Optional::stream)
			.collect(Collectors.toList());
        Recommended Posts