3

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?

0

1 Answer 1

8

You can create a List of at most two Tokens and then check its size:

List<Token> filtered =
    listResult.stream()
              .filter(t -> t.getStatus().equals(TokenStatus.ACTIVE.code()))
              .limit(2)
              .collect(Collectors.toList());
if (filtered.size () != 1) {
    throw new new IllegalStateException(Messages.ONE_TOKEN_MUST_BE_ACTIVATED);
}
Token token = filtered.get(0);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.