Home > other >  Create right Stream API with java
Create right Stream API with java

Time:09-24

I have next code and I want create Stream API for this fragment:

for (Task task : deletedTasks) {
    if (!Objects.isNull(task.getUser())) {
        kafkaSenderTaskProducer.sendAutoRejectedTasksEvent(task.getId(), task.getUser().getId());
    } else {
        kafkaSenderTaskProducer.sendDeletedEvent(task);
    }
}

For second else condition I have code, but I don`t know how to type code for first condition

deletedTasks.stream()
            .filter(task -> Objects.isNull(task.getUser()))
            .forEach(kafkaSenderTaskProducer::sendDeletedEvent);

Can u give me some advice for create Stream API for first condition

CodePudding user response:

You don't need to use stream or filter here. As simple forEach will work for you. Unnecessary use of stream in the code will have performance issue. You can do it as below:

deletedTasks.forEach(task -> {
    if(task.getUser() == null) {
       kafkaSenderTaskProducer.sendDeletedEvent(task);
    } else {
       kafkaSenderTaskProducer.sendAutoRejectedTasksEvent(task.getId(), task.getUser().getId());
    }
})
  • Related