Create a simple counter in java 11, using java IntSupplier - Then test it using IntStream - a functional programming way.
Author : Anurag Anand
We will create a simple counter in java.
- It will have a default initialization of 0.
- It will have a constructor, which can be used to set the seed value of this counter.
- It will implement Iterator interface
- It will implement IntSupplier interface
package com.refactored.util;
import java.util.Iterator;
import java.util.function.IntSupplier;
public class Counter implements Iterator<Integer>, IntSupplier {
private int count = 0;
public Counter(){}
public Counter(int seed) {
count = seed;
}
@Override
public Integer next() {
return ++count;
}
@Override
public boolean hasNext(){
return count < Integer.MAX_VALUE;
}
@Override
public int getAsInt() {
return next().intValue();
}
}
private int count = 0; this is our variable which stores the count. And it is initialized with 0.
public Counter(){} this is our default constructor.
This is the second constructor, which initializes the counter with the given value.
public Counter(int seed) {
count = seed;
}
Now, We are going to create a class to use this counter with it's default value.
package com.refactored.util;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
public class UseCounter {
public static void main(String[] args) {
Counter counter = new Counter();
//Print the 10 elements
IntPredicate limit_10 = limitStream(10);
IntStream.generate(counter)
.takeWhile(limit_10)
.forEach(System.out::println);
}
private static IntPredicate limitStream(int lastCount) {
return (int value) -> (value <= lastCount);
}
}
After running this, we get the following output.
1
2
3
4
5
6
7
8
9
10
Now, we will create a counter with seed value of 100, and print from 101 to 110.
Modified portion of code looks like this.
int seed = 100;
Counter counter = new Counter(seed);
//Print the 10 elements
IntPredicate limit_10 = limitStream(seed+10);
Let us, run this.
101
102
103
104
105
106
107
108
109
110
So, We have successfully created a counter. :)
Happy coding.