Looking for how to use Java lambda functions so Consumer can process all objects provided by a Supplier, and get rid of the explicit while
loop and null
checks.
I have a Supplier of String keys for a database and I want to use a Consumer to process each of those keys.
Supplier<String> keyGen = new SimpleKeySupplier(keyPrefix, numKeys);
Consumer<String> consumer = (String key) -> System.out.println("key="+key);
I want consumer
to process each key supplied by keyGen
and tried the following. It works but I am sure that there must be a more concise way of using lambda functions to make this simpler.
// Test that the correct keys have been populated.
Supplier<String> keyGen = new SimpleKeySupplier(keyPrefix, NumKeys);
String k = keyGen.get();
while(k != null) {
consumer.accept(k);
k = keyGen.get();
}
SimpleKeySupplier works, and a simplified version is presented below:
import java.util.function.Supplier;
public class SimpleKeySupplier implements Supplier<String> {
private final String keyPrefix;
private final int numToGenerate;
private int numGenerated;
public SimpleKeySupplier(String keyPrefix, int numRecs) {
this.keyPrefix = keyPrefix;
numToGenerate = numRecs;
numGenerated = 0;
}
@Override
public String get() {
if (numGenerated >= numToGenerate)
return null;
else
return (keyPrefix + numGenerated++);
}
}
The Consumer in this example is greatly simplified for posting on StackOverflow.
You may do it like so, with the new capabilities added in Java9.
Stream.generate(keyGen).takeWhile(Objects::nonNull).forEach(consumer);
Try this
Supplier<String> keyGen = new SimpleKeySupplier(keyPrefix, numKeys);
Consumer<String> consumer = (String key) -> System.out.println("key="+key);
Stream.generate(keyGen).filter(s -> s !=null).limit(NumKeys).forEach(consumer);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With