0

I am trying to use stream with my code below. My problem is my return value. This piece of code return an Optional not a boolean:

ogps.stream().filter(elt -> (elt.getLineNumbers() != null && !vg.getLineNumbers().isEmpty())).findFirst();

Can you please guide me? Thks

//The original code
public static boolean isOrderOk(List<OrderGroup> ogps) {
        if (ogps == null || ogps.isEmpty()) {
            return true;
        }
        for (OrderGroup elt : ogps) {
            if (elt.getLineNumbers() != null && !vg.getLineNumbers().isEmpty()) {
                return false;
            }
        }
        return true;
}

//The new code with stream usage
public static boolean isOrderOk(List<OrderGroup> ogps) {
        if (ogps == null || ogps.isEmpty()) {
            return true;
        }
        return ogps.stream()
                .filter(elt -> (elt.getLineNumbers() != null && !vg.getLineNumbers().isEmpty()))
                .findFirst();
        return true;
}
2
  • 2
    See anyMatch. It is a short-circuit terminal operation made exactly for this purpose. Commented Apr 28, 2017 at 12:55
  • 1
    And if you need the value from the Optional use it's get method Commented Apr 28, 2017 at 12:55

2 Answers 2

1

You are probably looking for something like:

public static boolean isOrderOk(List<OrderGroup> ogps) {
    if (ogps == null || ogps.isEmpty()) {
        return true;
    }
    return ! ogps.stream()
        .anyMatch(elt -> (elt.getLineNumbers() != null && !vg.getLineNumbers().isEmpty()));
}
Sign up to request clarification or add additional context in comments.

Comments

0

The reason is that you are using findFirst method of stream class and it returns Optional type as you can see here.

Comments

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.