Determines that any of the items returned in the given iterator evaluate to true against the given predicate. - Java java.util.function

Java examples for java.util.function:Predicate

Description

Determines that any of the items returned in the given iterator evaluate to true against the given predicate.

Demo Code


//package com.java2s;

import java.util.*;

import java.util.function.Predicate;

public class Main {
    /**/*  ww  w. ja  v a 2  s. c  om*/
     * Determines that any of the items returned in the given iterator evaluate to true against
     * the given predicate. For empty items, will return false.
     *
     * @param items The iterable items that will be evaluated.
     * @param predicate The predicate used to evaluate against.
     * @param <T> The type of items
     * @return True if any the items evaluated to true on the predicate.
     * @throws NullPointerException if iterable or predicate are null.
     */
    public static <T> boolean any(final Iterable<T> items,
            final Predicate<T> predicate) {
        return inBetween(items, predicate, 1, 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