Determines that at least the given number of the items evaluate to true against the given predicate. - Java java.util.function

Java examples for java.util.function:Predicate

Description

Determines that at least the given number of the items evaluate to true against the given predicate.

Demo Code


//package com.java2s;

import java.util.*;

import java.util.function.Predicate;

public class Main {
    /**/*from   w  w  w  .  ja  v a 2s  . co m*/
     * Determines that at least the given number of the items evaluate to true against
     * the given predicate.
     *
     * @param items The iterable items that will be evaluated.
     * @param predicate The predicate used to evaluate against.
     * @param atLeast The minimum number of items that need to be evaluated to true.
     * @param <T> The type of items
     * @return True if at least the given number the items evaluated to true on the predicate.
     * @throws NullPointerException if iterable or predicate are null.
     * @throws IllegalArgumentException If atLeast is less then 0.
     */
    public static <T> boolean atLeast(final Iterable<T> items,
            final Predicate<T> predicate, int atLeast) {
        return inBetween(items, predicate, atLeast, Integer.MAX_VALUE);
    }

    /**
     * Determines that the items in an iterator evaluate to true on the given predicate between the given minimum
     * and maximum number of times.
     *
     * @param items The iterable items that will be evaluated.
     * @param predicate The predicate used to evaluate against.
     * @param atLeast The minimum number of items that need to be evaluated to true.
     * @param atMost The maximum number of items that can to be evaluated to true.
     * @param <T> The type of items
     * @return True if the items evaluate to true within the range of times given.
     * @throws NullPointerException if iterable or predicate are null.
     * @throws IllegalArgumentException If either atLeast or atMost is less then 0 or atMost < atLeast
     */
    public static <T> boolean inBetween(final Iterable<T> items,
            final Predicate<T> predicate, int atLeast, int atMost) {
        if (atLeast < 0 || atMost < 0 || (atMost < atLeast))
            throw new IllegalArgumentException(
                    "atLeast and "
                            + "atMost values must not be negative and atMost cannot be less then atLeast.");

        //
        Iterator<T> itr = items.iterator();
        int count = 0;

        for (T item : items) {
            if (predicate.test(item))
                count++;

            //Check if we can return early
            if ((count == atLeast && atMost == Integer.MAX_VALUE)
                    || count > atMost)
                break;
        }
        return count >= atLeast && count <= atMost;
    }
}

Related Tutorials