Reputation: 5472
This works well and all:
// ActorDao
public Optional<Actor> read(long id) {
return Optional.ofNullable(actors.get((int) id));
}
public List<Actor> readAll() {
// Return a list of actors from db
}
// Demo
public static Actor getActor(String firstName, String lastName) {
Dao<Actor> actorDao = new ActorDao();
long id = 0;
for (Actor actor : actorDao.readAll()) {
if (firstName.equalsIgnoreCase(actor.getFirstName()) && lastName.equalsIgnoreCase(actor.getLastName())) {
id = actor.getId() - 1; // actor_id in db starts at 1
return actorDao.read(id).get();
}
}
return null;
}
What would be the more elegant way in Java8+?
Upvotes: 0
Views: 49
Reputation: 50756
return actorDao.readAll()
.stream()
.filter(actor -> firstName.equalsIgnoreCase(actor.getFirstName()))
.filter(actor -> lastName.equalsIgnoreCase(actor.getLastName()))
.map(actor -> actorDao.read(actor.getId() - 1).get())
.findFirst()
.orElse(null);
Upvotes: 1