How to convert below method to Java 8 inline function?

Viewed 1159

I need to convert below method java 8 inline function. need some expert help and explanation to do this.

@Override
public boolean a(final Collection<DoseDetailMutableDTO> detailModels) {
    for (DoseDetailMutableDTO dd : detailModels) {
         final boolean doseDetailTextScheduled = isDoseDetailTextScheduled(dd, 1);
         if (doseDetailTextScheduled) {
             return true;
         }
    }
    return false;
}

and Are there any short cut to do this intelj IDE ?

3 Answers

You can make use of Stream.anyMatch as:

public boolean a(final Collection<DoseDetailMutableDTO> detailModels) {
    return detailModels.stream()
                       .anyMatch(dd -> isDoseDetailTextScheduled(dd, 1));
}

returns true if any elements of the stream match the provided predicate, otherwise false

Edit: (from comments)

The control to learn for such suggested shortcuts on IntelliJ IDEA is Ctrl+Space or on MacOS can use Alt+Enter as well.

We can try using a stream here:

@Override
public boolean a (final Collection<DoseDetailMutableDTO> detailModels) {
    return detailModels.stream()
               .filter(x -> isDoseDetailTextScheduled(x, 1))
               .findFirst()
               .orElse(false);
}

Actually, to make your method null safe, in the event that the input list might be null, we can try this:

@Override
public boolean a (final Collection<DoseDetailMutableDTO> detailModels) {
    return Optional.ofNullable(detailModels)
                   .map(Collection::stream)
                   .orElseGet(Stream::empty)
                   .filter(x -> isDoseDetailTextScheduled(x, 1))
                   .findFirst()
                   .orElse(false);
}

You can use anyMatch for this. Since the second parameter to the function is constant you can write a method that calls isDoseDetailTextScheduled. I think it becomes even more concise:

public boolean a(final Collection<DoseDetailMutableDTO> detailModels) {
   return detailModels.stream().anyMatch(this::isDoseDetailTextScheduledOne);
}

public boolean isDoseDetailTextScheduledOne(DoseDetailMutableDTO dto) {
    return isDoseDetailTextScheduled(dto, 1);
}
Related