@Test public void IntPredicate() { // TODO - Convert the anonymous inner class to a lambda IntPredicate predicate = new IntPredicate() { @Override public boolean test(int value) { return value % 2 == 0; } }; List<Integer> evens = IntStream.rangeClosed(1, 5).filter(predicate).boxed().collect(Collectors.toList()); Assert.assertEquals(Arrays.asList(2, 4), evens); List<Integer> odds = IntStream.rangeClosed(1, 5).filter(predicate.negate()).boxed().collect(Collectors.toList()); Assert.assertEquals(Arrays.asList(1, 3, 5), odds); Assert.assertTrue(IntStream.rangeClosed(1, 5).anyMatch(predicate)); Assert.assertFalse(IntStream.rangeClosed(1, 5).allMatch(predicate)); Assert.assertFalse(IntStream.rangeClosed(1, 5).noneMatch(predicate)); }
/** * Constructs a quantified predicate matcher for an {@code IntStream}. * * @param predicate the {@code Predicate} to apply to stream elements * @param matchKind the kind of quantified match (all, any, none) * @return a {@code TerminalOp} implementing the desired quantified match * criteria */ public static TerminalOp<Integer, Boolean> makeInt(IntPredicate predicate, MatchKind matchKind) { Objects.requireNonNull(predicate); Objects.requireNonNull(matchKind); class MatchSink extends BooleanTerminalSink<Integer> implements Sink.OfInt { MatchSink() { super(matchKind); } @Override public void accept(int t) { if (!stop && predicate.test(t) == matchKind.stopOnPredicateMatches) { stop = true; value = matchKind.shortCircuitResult; } } } return new MatchOp<>(StreamShape.INT_VALUE, matchKind, MatchSink::new); }
@Override public final IntStream filter(IntPredicate predicate) { Objects.requireNonNull(predicate); return new StatelessOp<Integer>(this, StreamShape.INT_VALUE, StreamOpFlag.NOT_SIZED) { @Override Sink<Integer> opWrapSink(int flags, Sink<Integer> sink) { return new Sink.ChainedInt<Integer>(sink) { @Override public void begin(long size) { downstream.begin(-1); } @Override public void accept(int t) { if (predicate.test(t)) downstream.accept(t); } }; } }; }
/** * Adapted from StackOverflow {@linkplain so http://stackoverflow.com/questions/20746429/limit-a-stream-by-a-predicate} * * @param splitr the original Spliterator * @param predicate the predicate * @return a Spliterator.OfInt */ private static Spliterator.OfInt takeIntWhile(Spliterator.OfInt splitr, IntPredicate predicate) { return new Spliterators.AbstractIntSpliterator(splitr.estimateSize(), 0) { boolean stillGoing = true; @Override public boolean tryAdvance(IntConsumer consumer) { if (stillGoing) { boolean hadNext = splitr.tryAdvance((int elem) -> { if (predicate.test(elem)) { consumer.accept(elem); } else { stillGoing = false; } }); return hadNext && stillGoing; } return false; } }; }
/** * Estimates the size of a filter applied to an IMembershipSet * @return an approximation of the size based on sampling. May return 0. * There are no strict guarantees on the quality of the approximation, * but is good enough for initialization of a hash table sizes. */ public static int estimateSize(final IMembershipSet baseMap, final IntPredicate filter) { final IMembershipSet sampleSet = baseMap.sample(sizeEstimationSampleSize, 0); if (sampleSet.getSize() == 0) return 0; int eSize = 0; final IRowIterator iter = sampleSet.getIterator(); int curr = iter.getNextRow(); while (curr >= 0) { if (filter.test(curr)) eSize++; curr = iter.getNextRow(); } return (baseMap.getSize() * eSize) / sampleSet.getSize(); }
/** * @throws ExecutionException * Added for the call to 'cache.get(..)'. */ @Test @SuppressWarnings(CompilerWarnings.UNCHECKED) public void shouldWrapExecutionExceptionInMemoizationException() throws ExecutionException { // given final IntPredicate predicate = a -> true; final IntFunction<String> keyFunction = a -> "key"; final Cache<String, Boolean> cache = Mockito.mock(Cache.class); given(cache.get(any(), any())).willThrow(ExecutionException.class); final GuavaCacheBasedIntPredicateMemoizer<String> memoizer = new GuavaCacheBasedIntPredicateMemoizer<>( cache, keyFunction, predicate); // when thrown.expect(MemoizationException.class); // then memoizer.test(123); }
/** * */ @Test @SuppressWarnings(CompilerWarnings.UNUSED) public void shouldRequireNonNullPredicate() { // given final ConcurrentMap<Integer, Boolean> cache = new ConcurrentHashMap<>(); final IntPredicate predicate = null; final IntFunction<Integer> keyFunction = Integer::valueOf; // when thrown.expect(NullPointerException.class); thrown.expectMessage("Cannot memoize a NULL Predicate - provide an actual Predicate to fix this."); // then new ConcurrentMapBasedIntPredicateMemoizer<>(cache, keyFunction, predicate); }
/** * */ @Test public void shouldTestGivenValue() { // given final IntPredicate predicate = Mockito.mock(IntPredicate.class); final IntFunction<String> keyFunction = a -> "key"; final Cache<String, Boolean> cache = CacheBuilder.newBuilder().build(); // when final GuavaCacheBasedIntPredicateMemoizer<String> memoizer = new GuavaCacheBasedIntPredicateMemoizer<>( cache, keyFunction, predicate); // then memoizer.test(123); Mockito.verify(predicate).test(123); }
void scanAllVersion(IntPredicate predicate) { SkipListScanner scanner = this.slist.scan(0, true, 0, true); if (scanner == null) { return; } while (scanner.next()) { long pHead = scanner.getValuePointer(); if (pHead == 0) { continue; } int oHead = Unsafe.getInt(pHead); if (oHead == 0) { continue; } for (ListNode i=ListNode.create(this.base, oHead); i!=null; i=i.getNextNode()) { boolean cont = predicate.test(i.getOffset()); if (!cont) { return; } } } }
private void assertIntPredicates(Supplier<IntStream> source, Kind kind, IntPredicate[] predicates, boolean... answers) { for (int i = 0; i < predicates.length; i++) { setContext("i", i); boolean match = intKinds.get(kind).apply(predicates[i]).apply(source.get()); assertEquals(answers[i], match, kind.toString() + predicates[i].toString()); } }
@Test(dataProvider = "IntStreamTestData", dataProviderClass = IntStreamTestDataProvider.class) public void testIntStream(String name, TestData.OfInt data) { for (IntPredicate p : INT_PREDICATES) { setContext("p", p); for (Kind kind : Kind.values()) { setContext("kind", kind); exerciseTerminalOps(data, intKinds.get(kind).apply(p)); exerciseTerminalOps(data, s -> s.filter(ipFalse), intKinds.get(kind).apply(p)); exerciseTerminalOps(data, s -> s.filter(ipEven), intKinds.get(kind).apply(p)); } } }
private void checkAndSetOrder(IntPredicate expectedValue, IntUnaryOperator newValue) { if (!expectedValue.test(invocationOrder)) { throw new TestSupport.AssertionFailedException( expectedValue + " -> " + newValue); } invocationOrder = newValue.applyAsInt(invocationOrder); }
@Test public void should_verify_an_actual_int_predicate_is_conform_to_an_expected_result() { assertThat(resultOf(() -> { gwtMock.whenAnEventHappensInRelationToAnActionOfTheConsumer(); return (IntPredicate) number -> number < 100; }).accepts(99)).hasSameClassAs(assertThat((IntPredicate) t -> t == 0)); }
/** * Constructor * @param start the start for range, inclusive * @param end the end for range, exclusive * @param step the step increment * @param excludes optional predicate to exclude elements in this range */ RangeOfInts(int start, int end, int step, IntPredicate excludes) { super(start, end); this.start = start; this.end = end; this.step = step; this.ascend = start <= end; this.excludes = excludes; }
public List<Integer> filterNumbersWithPredicate(final List<Integer> numbers, IntPredicate predicate) { List<Integer> filteredNumbers = new ArrayList<>(); for (Integer number : numbers) { if (predicate.test(number)) { filteredNumbers.add(number); } } return filteredNumbers; }
@SuppressWarnings(CompilerWarnings.NLS) ConcurrentMapBasedIntPredicateMemoizer( final ConcurrentMap<KEY, Boolean> cache, final IntFunction<KEY> keyFunction, final IntPredicate predicate) { super(cache); this.keyFunction = keyFunction; this.predicate = requireNonNull(predicate, "Cannot memoize a NULL Predicate - provide an actual Predicate to fix this."); }
/** * */ @Test public void shouldMemoizeIntPredicate() { // given final IntPredicate predicate = a -> true; // when final IntPredicate memoize = JCacheMemoize.intPredicate(predicate); // then Assert.assertNotNull("Memoized IntPredicate is NULL", memoize); }
/** * */ @Test public void shouldAcceptCacheAndPredicate() { // given final ConcurrentMap<Integer, Boolean> cache = new ConcurrentHashMap<>(); final IntPredicate predicate = input -> true; final IntFunction<Integer> keyFunction = Integer::valueOf; // when final ConcurrentMapBasedIntPredicateMemoizer<Integer> memoizer = new ConcurrentMapBasedIntPredicateMemoizer<>( cache, keyFunction, predicate); // then Assert.assertNotNull("Memoizer is NULL", memoizer); }
@Test public void allMatch() { IntPredicate p = i -> true; boolean result = this.parallelStreamSupportMock.allMatch(p); verify(this.delegateMock).allMatch(p); assertTrue(result); }
/** * */ @Test public void shouldMemoizeIntPredicateWithKeyFunction() { // given final IntPredicate predicate = a -> true; final IntFunction<String> keyFunction = a -> "key"; // when final IntPredicate memoize = CaffeineMemoize.intPredicate(predicate, keyFunction); // then Assert.assertNotNull("Memoized IntPredicate is NULL", memoize); }
/** * */ @Test public void shouldMemoizeIntPredicate() { // given final IntPredicate predicate = a -> true; // when final IntPredicate memoize = GuavaMemoize.intPredicate(predicate); // then Assert.assertNotNull("Memoized IntPredicate is NULL", memoize); }
/** * Find the elements of this range for which an int -> boolean predicate is true * * @param predicate the int -> boolean predicate * @return */ public List<Integer> filter(final IntPredicate predicate) { JointCallingUtils.nonNull(predicate, "predicate may not be null"); final List<Integer> result = new ArrayList<>(); forEach(i -> {if (predicate.test(i)) result.add(i); } ); return result; }
/** * Return a membership containing only the rows in the current one where * the predicate evaluates to true. * @param predicate Predicate evaluated for each row. */ default IMembershipSet filter(IntPredicate predicate) { int estimatedSize = MembershipSetFactory.estimateSize(this, predicate); IMutableMembershipSet ms = MembershipSetFactory.create(this.getSize(), estimatedSize); IRowIterator baseIterator = this.getIterator(); int tmp = baseIterator.getNextRow(); while (tmp >= 0) { if (predicate.test(tmp)) ms.add(tmp); tmp = baseIterator.getNextRow(); } return ms.seal(); }