3

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?

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! was close yet so far :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.