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?

Naman
  • 27,789
  • 26
  • 218
  • 353
Daniela Morais
  • 2,125
  • 7
  • 28
  • 49

1 Answers1

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);
Eran
  • 387,369
  • 54
  • 702
  • 768