Another approach to creating a separate factory class:
// streams/Bubble.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.function.*;
public class Bubble {
public final int i;
public Bubble(int n) {
i = n;
}
@Override
public String toString() {
return "Bubble(" + i + ")";
}
private static int count = 0;
public static Bubble bubbler() {
return new Bubble(count++);
}
}
// streams/Bubbles.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.stream.*;
public class Bubbles {
public static void main(String[] args) {
Stream.generate(Bubble::bubbler).limit(6).forEach(System.out::println); // method reference.
}
}
/* My Output:
Bubble(0)
Bubble(1)
Bubble(2)
Bubble(3)
Bubble(4)
Bubble(5)
*/
@FunctionalInterface
public interface Consumer<T>
Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer
is expected to operate via side-effects.
This is a functional interface whose functional method is accept(Object)
.
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/Bubble.java
3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/Bubbles.java
5. https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html