I have a list of tokens, this list must be contain just one element with active status. If there's no one element with status equals active I need to throw an exception.
I want to write this with lambda expresssions and this is my code:
List<Token> listResult = tokenRepository.findByReference(tokenRefId);
if (listResult == null || listResult.isEmpty()) {
throw new IllegalStateException(Messages.TOKEN_NOT_FOUND);
}
if (listResult.stream().filter(t -> t.getStatus().equals(TokenStatus.ACTIVE.code())).count() != 1) {
throw new IllegalStateException(Messages.ONE_TOKEN_MUST_BE_ACTIVATED);
}
Token token = listResult.stream().filter(t -> t.getStatus().equals(TokenStatus.ACTIVE.code()))
.findFirst().orElseThrow(() -> new IllegalStateException(Messages.ONE_TOKEN_MUST_BE_ACTIVATED));
Note that I throw the same exception twice. How can I check if there's just one element with active status and get it in the same lambda expression?