Can the return value for Supplier be incremental

334 views Asked by At

I am currently dealing with the topics Consumer and Supplier and have the following question. Can the return value for Supplier be incremental?

The following contrived example: I have a simple class Person with id and name. If I need for example for test purposes 10 persons, I want to generate them easily with sequential ids. How can I increment the id when getting it from supplier?

class Person {
    long id;
    String name;
}

To do something like this is my idea:

Supplier<Long> ids      = ()-> 1L;
Supplier<String> names  = ()-> UUID.randomUUID().toString();

for (int i = 0; i < 10; i++) {
    Person p = new Person(ids.get(), names.get());
    System.out.println(p);
}

Or is the construct Supplier not intended for such a use case?

1

There are 1 answers

2
Louis Wasserman On BEST ANSWER

Sure. You don't have to use a lambda.

new Supplier<Long>() {
  long x = 0;
  @Override public Long get() {
    return x++;
  }
}