2

Currently our implementation of a base method using Set<String> clients was as follows -

if (clients.isEmpty()) {
    throw new InvalidClientException();
}

for (String client : clients) {
    if (!myMay.containsKey(client)) {
        throw new InvalidClientException(client);
    }
}

I tried converting it using lambda expression as follows -

clients.stream().filter(client -> !myMay.containsKey(client) || clients.isEmpty())
            .forEach(InvalidClientException::new);

But this seems to be not working the same way, is the parameterised constructor call a miss here?

1 Answer 1

5

First of all, if the set is empty, the lambda passed to forEach won't be executed: an empty stream is empty, and filtering it won't add any element to it. Only potentially remove some.

Second, the lambda creates an exception. But it doesn't throw it.

You can use

if (clients.isEmpty() || clients.stream().anyMatch(client -> !myMay.containsKey(client))) {
    throw new InvalidClientException();
}

EDIT: I missed the fact that you wanted to pass the (first?) client not in the set to the exception. To do that, you can do

if (clients.isEmpty()) {
    throw new InvalidClientException();
}

clients.stream()
       .filter(client -> !myMay.containsKey(client))
       .findAny() // or .findFirst()
       .ifPresent(client -> {
           throw new InvalidClientException(client);
       });

That will only work if the exception is a runtime exception, though, because you can't throw a checked exception from a Consumer. If it's a checked exception and you really want to keep it a checked exception, you can use

if (clients.isEmpty()) {
    throw new InvalidClientException();
}

Optional<String> wrongClient = 
    clients.stream()
           .filter(client -> !myMay.containsKey(client))
           .findAny();
if (wrongClient.isPresent()) {
    throw new InvalidClientException(wrongClient.get());
}
Sign up to request clarification or add additional context in comments.

9 Comments

ohk, no way to use filter while streaming and throw the exception as well?
also how to handle throw new InvalidClientException(client) here?
You don't want to dilter. You want to find if an element of the stream is not in the myMay set. That's what anyMatch() does. Throwing an exception for every element not in the set doesn't make much sense, since as soon as the exception is thrown, the loop will stop.
i meant the parameterised call to InvalidClientException(client) where i need to pass the clients name which is invalid as well
the updated version doesn't seem to be working on my IDE, for the ifPresent part
|

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.