使用 lambda 返回列表中的匹配元素

这很好用:


// 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;

}

Java8+ 中更优雅的方式是什么?


慕少森
浏览 132回答 1
1回答

月关宝盒

return&nbsp;actorDao.readAll() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.filter(actor&nbsp;->&nbsp;firstName.equalsIgnoreCase(actor.getFirstName())) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.filter(actor&nbsp;->&nbsp;lastName.equalsIgnoreCase(actor.getLastName())) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.map(actor&nbsp;->&nbsp;actorDao.read(actor.getId()&nbsp;-&nbsp;1).get()) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.findFirst() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.orElse(null);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java