javavavr

Trying to convert a Try<List<Message>> to a Try<List<SummarizedMessage>> using Java Vavr


I'm able to "solve" this with the following (ugly and smelly) code:

List<Message> messages = messagesRepository.findAll().get();

return Try.success(
                    messages
                    .stream()
                    .map(m -> new SummarizedMessage(m.destination(), m.title(), m.date()))
                    .toList()
            );

But how can I avoid this get() and Try.success()?


Solution

  • You can use map and orElse.

    messagesRepository.findAll().map(messages -> messages.stream()
                         .map(m -> new SummarizedMessage(m.destination(), m.title(), m.date()))
                         .toList()).orElse(null);