Reputation: 41
Can you help me code the following using the Java 8 stream API?
SuperUser superUser = db.getSuperUser;
for (final Client client : superUser) {
if (cartData.getClient().equals(client.getUid())) {
client.setIsSelected(true);
break;
}
}
Thanks for your help!
Upvotes: 2
Views: 132
Reputation: 56413
In addition to the other answer, I'd like to add that calling cartData.getClient()
each time in the loop is sub-optimal instead cache it before the start of the loop as seen below:
T tempClient = cartData.getClient(); // where T is the type returned by getClient()
Then you can do:
superUser.stream() // or Arrays.steam(superUser) if superUser is an array
.filter(c -> tempClient.equals(c.getUid()))
.findFirst()
.ifPresent(client -> client.setIsSelected(true));
or:
superUser.stream() // or Arrays.steam(superUser) if superUser is an array
.filter(c -> tempClient.equals(c.getUid()))
.limit(1)
.forEach(client -> client.setIsSelected(true));
Upvotes: 4
Reputation: 4090
How to code this using Java 8 stream:
SuperUser superUser = db.getSuperUser;
for (final Client client : superUser) {
if (cartData.getClient().equals(client.getUid())) {
client.setIsSelected(true);
break;
}
}
For-each does not seem like the proper tool for this job. You could try:
superUser.stream()
.filter(c -> cartData.getClient().equals(c.getUid()))
.findFirst().ifPresent(c -> c.setIsSelected(true));
Upvotes: 2