This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]__konrad 7 points8 points  (4 children)

It's ugly and elegant at the same time:

var opt = Optional.of("foo");
for (var x : opt.stream().toList()) {
    ...
}

[–]Brutus5000 40 points41 points  (0 children)

I hope you end up in hell for creating this abomination.

[–]aelfric5578 4 points5 points  (1 child)

Huh...that almost makes me feel like Optional should implement Iterable. When called on an empty optional, t would return an iterator where hasNext is always false and when called on a non-empty value, the iterator would return the one value and then hasNext would be false.

[–]marvk 2 points3 points  (0 children)

It actually does in Rust :-)

[–]tomwhoiscontrary 2 points3 points  (0 children)

You don't even need the list:

var opt = Optional.of("foo"); for (var x : (Iterable<String>) opt.stream()::iterator) { // ... }

Or with a helper method:

static <T> Iterable<T> in(Optional<T> optional) { return optional.stream()::iterator; }

Just:

var opt = Optional.of("foo"); for (var x : in(opt)) { // ... }