Java examples for java.util.function:Predicate
Determines that at most the given number of the items evaluate to true against the given predicate.
//package com.java2s; import java.util.*; import java.util.function.Predicate; public class Main { /**//from w w w . j a va 2 s .c om * Determines that at most 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 atMost The maximum number of items that can to be evaluated to true. * @param <T> The type of items * @return True if at most the given number the items evaluated to true on the predicate. * @throws NullPointerException if iterable or predicate are null. * @throws IllegalArgumentException If atMost is less then 0. */ public static <T> boolean atMost(final Iterable<T> items, final Predicate<T> predicate, int atMost) { return inBetween(items, predicate, 0, atMost); } /** * 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; } }