Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Lambda functions to Consume all objects provided by a Supplier

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.

like image 864
ScottK Avatar asked Dec 19 '18 04:12

ScottK


2 Answers

You may do it like so, with the new capabilities added in Java9.

Stream.generate(keyGen).takeWhile(Objects::nonNull).forEach(consumer);
like image 135
Ravindra Ranwala Avatar answered Sep 23 '22 23:09

Ravindra Ranwala


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);
like image 26
TongChen Avatar answered Sep 20 '22 23:09

TongChen