您可以使用Java 8流API帮我编写以下代码吗?

SuperUser superUser = db.getSuperUser;
for (final Client client : superUser) {
    if (cartData.getClient().equals(client.getUid())) {
        client.setIsSelected(true);
        break;
    }
}


谢谢你的帮助!

最佳答案

除了其他答案,我想补充一下,每次在循环中调用cartData.getClient()都是次优的,而是在循环开始之前对其进行缓存,如下所示:

T tempClient = cartData.getClient();  // where T is the type returned by getClient()


然后,您可以执行以下操作:

  superUser.stream()  // or Arrays.steam(superUser) if superUser is an array
           .filter(c -> tempClient.equals(c.getUid()))
           .findFirst()
           .ifPresent(client -> client.setIsSelected(true));


要么:

superUser.stream() // or Arrays.steam(superUser) if superUser is an array
         .filter(c -> tempClient.equals(c.getUid()))
         .limit(1)
         .forEach(client -> client.setIsSelected(true));

09-26 09:12