OnJava8-Examples/generics/coffee/CoffeeSupplier.java

70 lines
1.9 KiB
Java
Raw Normal View History

2015-11-03 12:00:44 -08:00
// generics/coffee/CoffeeSupplier.java
// (c)2021 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-07-28 12:48:23 -06:00
// {java generics.coffee.CoffeeSupplier}
2015-06-15 17:47:35 -07:00
package generics.coffee;
import java.util.*;
2015-11-03 12:00:44 -08:00
import java.util.function.*;
2016-01-25 18:05:55 -08:00
import java.util.stream.*;
2020-10-07 17:06:42 -06:00
import java.lang.reflect.InvocationTargetException;
2015-06-15 17:47:35 -07:00
2015-11-03 12:00:44 -08:00
public class CoffeeSupplier
implements Supplier<Coffee>, Iterable<Coffee> {
2015-06-15 17:47:35 -07:00
private Class<?>[] types = { Latte.class, Mocha.class,
Cappuccino.class, Americano.class, Breve.class, };
private static Random rand = new Random(47);
2015-11-03 12:00:44 -08:00
public CoffeeSupplier() {}
2015-06-15 17:47:35 -07:00
// For iteration:
private int size = 0;
2015-11-03 12:00:44 -08:00
public CoffeeSupplier(int sz) { size = sz; }
@Override public Coffee get() {
2015-06-15 17:47:35 -07:00
try {
return (Coffee)
2020-10-07 17:06:42 -06:00
types[rand.nextInt(types.length)]
.getConstructor().newInstance();
2015-06-15 17:47:35 -07:00
// Report programmer errors at run time:
2020-10-07 17:06:42 -06:00
} catch(InstantiationException |
NoSuchMethodException |
InvocationTargetException |
IllegalAccessException e) {
2015-06-15 17:47:35 -07:00
throw new RuntimeException(e);
}
}
class CoffeeIterator implements Iterator<Coffee> {
int count = size;
@Override
public boolean hasNext() { return count > 0; }
@Override public Coffee next() {
2015-06-15 17:47:35 -07:00
count--;
2015-11-03 12:00:44 -08:00
return CoffeeSupplier.this.get();
2015-06-15 17:47:35 -07:00
}
@Override
public void remove() { // Not implemented
throw new UnsupportedOperationException();
}
}
@Override public Iterator<Coffee> iterator() {
2015-06-15 17:47:35 -07:00
return new CoffeeIterator();
}
public static void main(String[] args) {
2016-01-25 18:05:55 -08:00
Stream.generate(new CoffeeSupplier())
.limit(5)
.forEach(System.out::println);
2015-11-03 12:00:44 -08:00
for(Coffee c : new CoffeeSupplier(5))
2015-06-15 17:47:35 -07:00
System.out.println(c);
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Americano 0
Latte 1
Americano 2
Mocha 3
Mocha 4
Breve 5
Americano 6
Latte 7
Cappuccino 8
Cappuccino 9
2015-09-07 11:44:36 -06:00
*/