Determines that the items in an iterator evaluate to true on the given predicate between the given minimum and maximum number of times. - Java java.util

Java examples for java.util:Iterator

Description

Determines that the items in an iterator evaluate to true on the given predicate between the given minimum and maximum number of times.

Demo Code


//package com.java2s;

import java.util.*;

import java.util.function.Predicate;

public class Main {
    /**//from w w w . j av  a 2s .  co  m
     * 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