Search code examples
javajava-stream

How to check elements count and throw an exception in the middle of the stream?


I have a stream of elements and want to get only one element from stream and throw exceptions if there are more than one element in the stream and if there is no elemenets at all. Is it possible to make with Stream?

public Entity getEntityByValue(String value) {
        return entityService.getEntitiesByValue(value)
                .stream
                // check here count of entities and throw a MultiMatchException if more than one entity is present
                .findAny()
                .orElseThrow(() -> throw NoEntitiesFoundException()); //no entities found
    }

I thought of using .reduce(a, b -> throw MultiMatchException) and throw the exception if the second element is exists but couldn't combine it with other code


Solution

  • You were close:

    stream.reduce((i1, i2) -> { throw new RuntimeException(); })
          .orElseThrow(() -> new RuntimeException());