Reputation: 647
I have following class
class Customer {
List<String> itemCodes;
String customerId;
}
Lets say I have List of customers and I need to search the customerId of a first customer in this list with a specific itemCode.
The way I do currently is as follows
for (Customer cust : Customers) {
if (cust.getItemCodes() != null && cust.getItemCodes().contains("SPECIFIC_CODE")) {
return cust.getCustomerId();
}
}
I wanted to convert above loop using Java8
The best I could get right now is
customers.stream().flatMap(cust -> cust.getItemCodes().stream()).filter(code -> code.equals("SPECIFIC_CODE")).findFirst();
But this returns me Optional with value as a item code itself. But I need the customerId of that person. Problem is, I am not sure how I can access previous value of lambda here?
So is there any way I can use java8 to replace above loop?
Upvotes: 3
Views: 270
Reputation: 394016
You don't need flatMap
here. Just use filter
to locate matching Customer
and map
to obtain the CustomerId
of that Customer
.
return customers.stream()
.filter(c -> c.getItemCodes() != null && c.getItemCodes().contains("SPECIFIC_CODE"))
.map(Customer::getCustomerId)
.findFirst()
.orElse(null); // default value in case no match is found
Upvotes: 4