J
J
Jake Taylor2021-10-29 17:28:55
Java
Jake Taylor, 2021-10-29 17:28:55

How to merge two Streams when the first one might throw an exception in Java?

There are two DAO layers:
1. The `TagDao` layer with the `Optional findByName(String tagName) {...}`
method 1. The `GiftCertificateDao` layer with the `Set findByTag(Tag tag) {...}` method

In the service I compiled a method for obtaining a gift certificate (GiftCertificate) by tag (Tag):

@Override
    public Set<GiftCertificateDto> findByTagName(String tagName) {
        Tag tag = tagDao.findByName(tagName)
                .orElseThrow(() -> new EntityNotFoundException(MESSAGE_ENTITY_NOT_FOUND_EXCEPTION));

        return giftCertificateDao.findByTag(tag).stream()
                .map(giftCertificate -> modelMapper.map(giftCertificate, GiftCertificateDto.class))
                .collect(Collectors.toSet());
    }


Now I do not understand how to combine these two streams into one. As I tried: first I tried to throw an exception by calling the ` .orElseThrow()` method, but this is the "final" method, after which it is impossible to call, for example, `map()`.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-10-29
@n199a

return tagDao.findByName(tagName)
    .map(tag -> giftCertificateDao.findByTag(tag)
        .stream()
        .map(giftCertificate -> modelMapper.map(giftCertificate, GiftCertificateDto.class))
        .collect(Collectors.toSet()))
    .orElseThrow(() -> new EntityNotFoundException(MESSAGE_ENTITY_NOT_FOUND_EXCEPTION));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question