Is there a way to simplify the following with a stream or something?
final List<Fruit> fruits = new ArrayList<>(fruitIds.size());
for (final long id : fruitIds) {
final var fruit = new Fruit();
fruit.setId(id);
fruits.add(fruit);
}
Thank you very much in advance
Using a constructor would be optimal. This assumes an int id.
But if you aren't allowed to modify your
Fruit class
creating another class to act as a Factory class would work. Again I am presumingid
is anint
.If you are only creating instances of Fruit in a single place in your code then the above would be of little use. In that case I would just stick with what you have.
Using the above, the stream solution would be
And with a constructor