Java 8流:For Each

时间:2018-04-14 16:09:01

标签: java java-8 java-stream

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

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

感谢您的帮助!

2 个答案:

答案 0 :(得分:4)

除了另一个答案之外,我想补充一点,每次在循环中调用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));

答案 1 :(得分:2)

如何使用Java 8流编码:

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

For-each似乎不适合这项工作。 你可以尝试:

superUser.stream()
         .filter(c -> cartData.getClient().equals(c.getUid()))
         .findFirst().ifPresent(c -> c.setIsSelected(true));