Last active
August 29, 2015 14:20
-
-
Save bassemZohdy/193b0d4abf1ce26c1d3e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Iterator; | |
import java.util.NoSuchElementException; | |
import java.util.Optional; | |
import java.util.Spliterator; | |
import java.util.Spliterators; | |
import java.util.concurrent.atomic.AtomicInteger; | |
import java.util.function.Supplier; | |
import java.util.stream.Stream; | |
import java.util.stream.StreamSupport; | |
public class IteratorOfSupplierMain { | |
public static void main(String[] args) { | |
Iterator<Model> iterator = IteratorOfSupplier.of(new ModelSupplier()); | |
Spliterator<Model> spliterator = Spliterators.spliteratorUnknownSize( | |
iterator, Spliterator.NONNULL); | |
Stream<Model> stream = StreamSupport.stream(spliterator, false); | |
stream.forEach(System.out::println); | |
System.out.println("Done"); | |
} | |
} | |
class IteratorOfSupplier<T> implements Iterator<T> { | |
Optional<T> next = Optional.empty(); | |
final private Supplier<T> supplier; | |
private IteratorOfSupplier(Supplier<T> supplier) { | |
this.supplier = supplier; | |
} | |
public static <T> IteratorOfSupplier<T> of(Supplier<T> supplier) { | |
return new IteratorOfSupplier<T>(supplier); | |
} | |
@Override | |
public boolean hasNext() { | |
if (next.isPresent()) { | |
return true; | |
} else { | |
next = Optional.ofNullable(supplier.get()); | |
return next.isPresent(); | |
} | |
} | |
@Override | |
public T next() { | |
if (next.isPresent() || hasNext()) { | |
T result = next.get(); | |
next = Optional.empty(); | |
return result; | |
} else { | |
throw new NoSuchElementException(); | |
} | |
} | |
} | |
class ModelSupplier implements Supplier<Model> { | |
private final AtomicInteger counter = new AtomicInteger(0); | |
@Override | |
public Model get() { | |
if (counter.get() < 100) | |
return new Model("name" + counter.incrementAndGet()); | |
return null; | |
} | |
} | |
class Model { | |
private String name; | |
public Model(String name) { | |
this.name = name; | |
} | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
@Override | |
public String toString() { | |
return "Model [" + (name != null ? "name=" + name : "") + "]"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment