I have a method called getBalance
where I have an enhanced for loop and inside the loop I return customer.getBalance();
I now want to change that method in to a Stream from Java 8 and I can't figure out how to do it since you cannot return something inside a stream.
The method:
public double getBalance(String personalNumber, int accountNumber) {
for (Customer customer : customers) {
if (customer.getPersonalNumber().equals(personalNumber)) {
return customer.getBalance(accountNumber);
}
}
return 0;
}
You can do that using filter
and findFirst
:
return customers.stream()
.filter(customer -> customer.getPersonalNumber().equals(personalNumber))
.findFirst()
.map(customer -> customer.getBalance(accountNumber))
.orElse(0);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.