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
CodePudding user response:
Using a constructor would be optimal. This assumes an int id.
class Fruit {
int id;
public Fruit(int id) {
this.id = id;
}
public void setId(int id) {
this.id = id;
}
}
for (Fruit id : fruitIds) {
Fruits.add(new Fruit(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 presuming id
is an int
.
List<Fruit> fruits = new ArrayList<>(fruitIds.size());
for (final var id : fruitIds) {
fruits.add(FruitFactory.instance(id));
}
class FruitFactory {
public static Fruit instance(int id) {
Fruit fruit = new Fruit();
fruit.setId(id);
return fruit;
}
}
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
List<Fruit> fruits =
fruitIds.stream().map(FruitFactory::instance).toList();
And with a constructor
List<Fruit> fruits = fruitIds.stream().map(Fruit::new).toList();