Home > other >  Validating elements of an ArrayList to match a parameter (Java)
Validating elements of an ArrayList to match a parameter (Java)

Time:09-17

I need a method that checks that at least 1 element of a list matches a parameter. I've figured it out, but this code is poor and slow.

private static void validateAdvertisements(List<Advertisement> advertisements) {
    List<Advertisement> inactiveAdvertisements = new ArrayList<>();

    for (Advertisement advertisement : advertisements)
        if (!advertisement.isActive()) inactiveAdvertisements.add(advertisement);

    if (inactiveAdvertisements.size() == advertisements.size()) throw new NoAdvertisementAvailableException();
}

Is there a getter way to do this?

CodePudding user response:

Make your logic short-circuit.

Since you need to throw an exception only if there are no active Advertisement instances in the list, when the first active element is encountered - break out from the loop.

private static void validateAdvertisements(List<Advertisement> advertisements) {
    boolean isActiveNotFound = true;
        
    for (Advertisement advertisement : advertisements) {
        if (advertisement.isActive()) isActiveNotFound = false;
        break;
    }
        
    if (isActiveNotFound) throw new NoAdvertisementAvailableException();
}

A stream-based solution using Stream.noneMatch(), this operation is short-circuit and exception would be thrown only if there are no active objects.

private static void validateAdvertisements(List<Advertisement> advertisements) {
    boolean isActiveNotFound = advertisements.stream()
        .noneMatch(Advertisement::isActive);
        
    if (isActiveNotFound) throw new NoAdvertisementAvailableException();
}

In case if NoAdvertisementAvailableException is a runtime exception, it can be propagated outside the functions implementing standard functional interfaces from the JDK, like Runnable.

Here's an example that makes use of the combination Stream.findFirst() Optional.ifPresentOrElse():

private static void validateAdvertisements(List<Advertisement> advertisements) {
    advertisements.stream()
        .filter(Advertisement::isActive)
        .findFirst()
        .ifPresentOrElse(s -> {},
            () -> { throw new NoAdvertisementAvailableException(); }
    );
}

CodePudding user response:

Came up with the solution using Streams

private static void validateAdvertisements(List<Advertisement> advertisements) {
    if (advertisements.stream().noneMatch(Advertisement::isActive)) throw new NoVideoAvailableException();
}
  • Related