Sasha
Sasha

Reputation: 81

java 8 stream if/else rewrite

Will you tell me how to implement beautifully logic in this method?

protected Map<QueueType, QueueContext> getQueueContexts() {
    List<QueueContext> queueContexts = QueueContext.parseConfigs(Config.KAFKA_QUEUES.get());
    return queueContexts.stream()
                    .collect(Collectors.toMap(QueueContext::getQueueType, Function.identity()));
    }

It is necessary to check if there is a QueueType.unknown in the List queueContexts and if there is, then write to the log, if not, then add to the Map.

I do just such a check, but it turns out that I'm collecting Map correctly, but all the logs are written that are, and I need to write only those that are unknown

return queueContexts.stream().filter(type -> type.getQueueType() != QueueType.unknown)
                    .peek(ls -> LOGGER.info(ls))
                    .collect(Collectors.toMap(QueueContext::getQueueType, Function.identity()));

Upvotes: 1

Views: 217

Answers (1)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59988

What about

return queueContexts.stream()
        .filter(type -> {
            if (type.getQueueType() != QueueType.unknown)
                return true;
            LOGGER.info(type);
            return false;
        })
        .collect(Collectors.toMap(QueueContext::getQueueType, Function.identity()));

or you can create a method to replace the core of filter:

private boolean isNotUnknown(QueueContext type){
    if (type.getQueueType() != QueueType.unknown)
        return true;
    LOGGER.info(type);
    return false;
}

and then:

return queueContexts.stream()
        .filter(this::isNotUnknown)
        .collect(Collectors.toMap(QueueContext::getQueueType, Function.identity()));

Upvotes: 1

Related Questions