2 ms·
You can turn a Stream<T> into an Iterator<T>, and since Iterable<T> is a functional interface whose single method supplies an Iterator<T>, you can make an Itera
by twic 8y ago
You can turn a Stream<T> into an Iterator<T>, and since Iterable<T> is a functional interface whose single method supplies an Iterator<T>, you can make an Iterable<T> by wrapping a Stream<T> in a simple lambda:
Iterable<ProductDisplayInfo> getDisplayList(List<Product> products) {
return () -> products.stream()
.filter(p -> p.getCategory() == 2 || p.getCategory() == 5 && isProductUnderDiscount(p))
.map(ProductDisplayInfo::new)
.iterator();
}
(E&OE - i haven't actually compiled this, but do this all the time!)
- bunderbunder 8y agoWhat happens when you try to iterate that iterable twice?
- jcheng 8y agoWhy wouldn't that work? The iterable returns a different iterator, backed by a different stream, each time.