1

I wonder how to replace this old school for loops with Java Streams:

public Long getStoreid(){
    for (PointDto point : tw.getPath().getPoints())) {
        for (PointOperationDto operation : point.getOperations()) {
            if (operation.isIncluded() {
                return point.getStoreId();
            }
        }
    }
}

I need to get storeId in the best possible way.\

UPDATE

After your answers the working version is:

tw.getPath().getPoints().stream()
                .filter(point -> point.getOperations().stream().anyMatch(PointOperation::isIncluded))
                .map(point::getStoreId)
                .findFirst()
                .orElse(null);

but now the question is how to use eg. Optional.ofNullable() to prevent NPE error because tw.getPath() can be null

2 Answers 2

2

I think you need that:

tw.getPath().getPoints().stream()
        .filter(point -> point.getOperations().stream().anyMatch(Operation::isIncluded))
        .map(Point::getStoreId)
        .findFirst()
        .orElse(0L);
Sign up to request clarification or add additional context in comments.

6 Comments

findFirst() might better translate the current implementation by OP.
YES! That is what I was looking for - I have to use anyMatch()... Thank you
@Dmitrii Bykov One more question - how to use Optional.ofNullable to prevent NPE error? tw.getPath() can be NULL... I tried with Optional.ofNullable(tw.getPath() but actually I don't have idea how to use it in this case
Optional.ofNullable(tw.getPath()).orElseGet(Collections.emptyList()).getPoints().stream() i think you need it
when you will use orElseGet() you should return Long or null, that's right. You also can use orElseThrow() and throw an exception. I don't know your logic. What do you want to return null or anyLong or throw exception...
|
2

The following operations are needed: map, filter, and findFirst:

public Long getStoreid() {
    return tw.getPath().getPoints().stream()
            .filter(Objects::isNonNull) // optional filter to prevent NPE
            .map(point -> point.getOperations().stream()
                .filter(Objects::isNonNull) // optional filter to prevent NPE
                .filter(PointOperationDto::isIncluded)
                .findFirst()
                .map(op -> point.getStoreId())
            )
            .findFirst()
            .orElse(null);
}

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.