Java Code Examples for java.util.function.Predicate#test()

The following examples show how to use java.util.function.Predicate#test() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReferencePipeline.java    From desugar_jdk_libs with GNU General Public License v2.0 6 votes vote down vote up
@Override
public final Stream<P_OUT> filter(Predicate<? super P_OUT> predicate) {
    Objects.requireNonNull(predicate);
    return new StatelessOp<P_OUT, P_OUT>(this, StreamShape.REFERENCE,
                                 StreamOpFlag.NOT_SIZED) {
        @Override
        Sink<P_OUT> opWrapSink(int flags, Sink<P_OUT> sink) {
            return new Sink.ChainedReference<P_OUT, P_OUT>(sink) {
                @Override
                public void begin(long size) {
                    downstream.begin(-1);
                }

                @Override
                public void accept(P_OUT u) {
                    if (predicate.test(u))
                        downstream.accept(u);
                }
            };
        }
    };
}
 
Example 2
Source File: MatchOps.java    From Java8CN with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a quantified predicate matcher for a Stream.
 *
 * @param <T> the type of stream elements
 * @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 <T> TerminalOp<T, Boolean> makeRef(Predicate<? super T> predicate,
        MatchKind matchKind) {
    Objects.requireNonNull(predicate);
    Objects.requireNonNull(matchKind);
    class MatchSink extends BooleanTerminalSink<T> {
        MatchSink() {
            super(matchKind);
        }

        @Override
        public void accept(T t) {
            if (!stop && predicate.test(t) == matchKind.stopOnPredicateMatches) {
                stop = true;
                value = matchKind.shortCircuitResult;
            }
        }
    }

    return new MatchOp<>(StreamShape.REFERENCE, matchKind, MatchSink::new);
}
 
Example 3
Source File: Partition.java    From IPAddress with Apache License 2.0 6 votes vote down vote up
/**
 * Applies the operation to each element of the partition,
 * returning true if they all return true, false otherwise
 * @param predicate
 * @param returnEarly returns as soon as one application of the predicate returns false (determining the overall result)
 * @return
 */
public boolean predicateForEach(Predicate<? super E> predicate, boolean returnEarly) {
	if(blocks == null) {
		return predicate.test(single);
	}
	boolean result = true;
	Iterator<? extends E> iterator = blocks;
	while(iterator.hasNext()) {
		if(!predicate.test(iterator.next())) {
			result = false;
			if(returnEarly) {
				break;
			}
		}
	}
	return result;
}
 
Example 4
Source File: TaskExecutorITCase.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
private SupplierWithException<Boolean, Exception> jobIsRunning(Supplier<CompletableFuture<? extends AccessExecutionGraph>> executionGraphFutureSupplier) {
	final Predicate<AccessExecution> runningOrFinished = ExecutionGraphTestUtils.isInExecutionState(ExecutionState.RUNNING).or(ExecutionGraphTestUtils.isInExecutionState(ExecutionState.FINISHED));
	final Predicate<AccessExecutionGraph> allExecutionsRunning = ExecutionGraphTestUtils.allExecutionsPredicate(runningOrFinished);

	return () -> {
		final AccessExecutionGraph executionGraph = executionGraphFutureSupplier.get().join();
		return allExecutionsRunning.test(executionGraph);
	};
}
 
Example 5
Source File: BlockInputReader.java    From incubator-nemo with Apache License 2.0 5 votes vote down vote up
private List<CompletableFuture<DataUtil.IteratorWithNumBytes>> readBroadcast(final Predicate<Integer> predicate) {
  final int numSrcTasks = InputReader.getSourceParallelism(this);
  final List<CompletableFuture<DataUtil.IteratorWithNumBytes>> futures = new ArrayList<>();
  for (int srcTaskIdx = 0; srcTaskIdx < numSrcTasks; srcTaskIdx++) {
    if (predicate.test(srcTaskIdx)) {
      final String blockIdWildcard = generateWildCardBlockId(srcTaskIdx);
      futures.add(blockManagerWorker.readBlock(
        blockIdWildcard, runtimeEdge.getId(), runtimeEdge.getExecutionProperties(), HashRange.all()));
    }
  }

  return futures;
}
 
Example 6
Source File: BaseStripeManager.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
boolean isActive(PaymentContext context,
                 EnumSet<ConfigurationKeys> additionalKeys,
                 Predicate<Map<ConfigurationKeys, ConfigurationManager.MaybeConfiguration>> subValidator) {
    var optionsToLoad = EnumSet.copyOf(additionalKeys);
    optionsToLoad.addAll(EnumSet.of(STRIPE_CC_ENABLED, PLATFORM_MODE_ENABLED, STRIPE_CONNECTED_ID));
    var configuration = configurationManager.getFor(optionsToLoad, context.getConfigurationLevel());
    return configuration.get(STRIPE_CC_ENABLED).getValueAsBooleanOrDefault(false)
        && (!configuration.get(PLATFORM_MODE_ENABLED).getValueAsBooleanOrDefault(false) || context.getConfigurationLevel().getPathLevel() == ConfigurationPathLevel.SYSTEM || configuration.get(STRIPE_CONNECTED_ID).isPresent())
        && subValidator.test(configuration);
}
 
Example 7
Source File: ActivePassiveClientIdTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private <T> void waitForPredicate(Predicate<T> predicate, long timeoutInMs) {
  long now = System.currentTimeMillis();
  while(predicate.test(null)) {
    if((System.currentTimeMillis() - now) > timeoutInMs) {
      fail("Waiting for attached client to disconnect timed-out");
    }
  }
}
 
Example 8
Source File: ReadableResourceProviderChain.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nullable
public IReadableResource getReadableResourceIf (@Nonnull final String sName,
                                                @Nonnull final Predicate <? super IReadableResource> aReturnFilter)
{
  // Use the first resource provider that supports the name
  for (final IReadableResourceProvider aResProvider : m_aReadingResourceProviders)
    if (aResProvider.supportsReading (sName))
    {
      final IReadableResource aRes = aResProvider.getReadableResource (sName);
      if (aReturnFilter.test (aRes))
        return aRes;
    }
  return null;
}
 
Example 9
Source File: monad5.java    From design-pattern-reloaded with MIT License 5 votes vote down vote up
public Validator<T> validate(Predicate<? super T> validation, String message) {
  try {
    if (!validation.test(t)) {
      throwables.add(new IllegalStateException(message));
    }
  } catch(RuntimeException e) {
    throwables.add(e);
  }
  return this;
}
 
Example 10
Source File: XDataFrameRow.java    From morpheus-core with Apache License 2.0 5 votes vote down vote up
@Override()
public final Optional<DataFrameValue<R,C>> last(Predicate<DataFrameValue<R,C>> predicate) {
    final DataFrameCursor<R,C> value = frame().cursor();
    value.atRowOrdinal(ordinal());
    for (int i=size()-1; i>=0; --i) {
        value.atColOrdinal(i);
        if (predicate.test(value)) {
            return Optional.of(value);
        }
    }
    return Optional.empty();
}
 
Example 11
Source File: B2.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public int indexOf(Predicate<? super IExpr> predicate, int fromIndex) {
	if (fromIndex == 1 && predicate.test(arg1)) {
		return 1;
	}
	if ((fromIndex == 1 || fromIndex == 2) && predicate.test(arg2)) {
		return 2;
	}
	return -1;
}
 
Example 12
Source File: ActivityIndexQueriesTest.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
default void storeSessions(Predicate<Session> save) {
    db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, RandomData::randomTime, TestConstants.PLAYER_ONE_NAME, serverUUID()));
    db().executeTransaction(new PlayerServerRegisterTransaction(player2UUID, RandomData::randomTime, TestConstants.PLAYER_TWO_NAME, serverUUID()));
    for (String world : worlds) {
        db().executeTransaction(new WorldNameStoreTransaction(serverUUID(), world));
    }

    for (Session session : RandomData.randomSessions(serverUUID(), worlds, playerUUID, player2UUID)) {
        if (save.test(session)) execute(DataStoreQueries.storeSession(session));
    }
}
 
Example 13
Source File: FileSystemUtils.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Populates an existing Path List, adding all of the paths below a given root path for which the
 * given predicate is true. Symbolic links are not followed, and may appear in the result.
 *
 * @throws IOException If the root does not denote a directory
 */
@ThreadSafe
public static void traverseTree(Collection<Path> paths, Path root, Predicate<Path> predicate)
    throws IOException {
  for (Path p : root.getDirectoryEntries()) {
    if (predicate.test(p)) {
      paths.add(p);
    }
    if (p.isDirectory(Symlinks.NOFOLLOW)) {
      traverseTree(paths, p, predicate);
    }
  }
}
 
Example 14
Source File: SchemaAnalyzer.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the given result, notifying a warning if the given predicate is true.
 */
private <T> T withWarningIf( T result, Predicate<T> isWarning, String reason)
  {
  if( isWarning.test( result))
    {
    notifyWarning( reason);
    }
  return result;
  }
 
Example 15
Source File: Preconditions.java    From datakernel with Apache License 2.0 4 votes vote down vote up
public static <T> T checkArgument(T argument, Predicate<T> predicate) {
	if (predicate.test(argument)) {
		return argument;
	}
	throw new IllegalArgumentException();
}
 
Example 16
Source File: TypeMemPtr.java    From aa with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override void walk( Predicate<Type> p ) { if( p.test(this) ) _obj.walk(p); }
 
Example 17
Source File: event_t.java    From mochadoom with GNU General Public License v3.0 4 votes vote down vote up
@Override
public <T> boolean ifKey(Predicate<? super T> scCondition, Function<? super ScanCode, ? extends T> extractor) {
    return scCondition.test(extractor.apply(sc));
}
 
Example 18
Source File: RetainedStateTestEnvironment.java    From Akatsuki with Apache License 2.0 4 votes vote down vote up
public void executeTestCaseWithFields(Set<? extends TestField> fieldList,
		Predicate<String> methodNamePredicate, FieldFilter accessorTypeFilter,
		Accessor accessor, Function<TestField, Integer> times) {
	Set<TestField> allFields = new HashSet<>(fieldList);

	for (Method method : Bundle.class.getMethods()) {

		// check correct signature and name predicate
		if (!checkMethodIsAccessor(method, accessor)
				|| !methodNamePredicate.test(method.getName())) {
			continue;
		}

		// find methods who's accessor type matches the given fields
		List<TestField> matchingField = allFields.stream()
				.filter(f -> filterTypes(method, accessor, accessorTypeFilter, f))
				.collect(Collectors.toList());

		// no signature match
		if (matchingField.isEmpty()) {
			continue;
		}

		// more than one match, we should have exactly one match
		if (matchingField.size() > 1) {
			throw new AssertionError(method.toString() + " matches multiple field "
					+ fieldList + ", this is ambiguous and should not happen."
					+ environment.printReport());
		}
		final TestField field = matchingField.get(0);
		try {
			if (accessor == Accessor.PUT) {
				method.invoke(verify(mockedBundle, times(times.apply(field))),
						eq(field.name), any(field.clazz));
			} else {
				method.invoke(verify(mockedBundle, times(times.apply(field))),
						eq(field.name));
			}
			allFields.remove(field);

		} catch (Exception e) {
			throw new AssertionError("Invocation of method " + method.getName()
					+ " on mocked object failed." + environment.printReport(), e);
		}
	}
	if (!allFields.isEmpty())
		throw new RuntimeException("While testing for accessor:" + accessor
				+ " some fields are left untested because a suitable accessor cannot be found: "
				+ allFields + environment.printReport());
}
 
Example 19
Source File: AuxiliaryOperation.java    From GyJdbc with Apache License 2.0 4 votes vote down vote up
default <T, R> S inIfAbsent(TypeFunction<T, R> function, Collection<?> args, Predicate<Collection> predicate) {
    if (predicate.test(args)) {
        return in(function, args);
    }
    return doNothing();
}
 
Example 20
Source File: CharacterList.java    From asteria-3.0 with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Searches the backing array for the first element encountered that matches
 * {@code filter}. This does not include elements with a value of
 * {@code null}.
 *
 * @param filter
 *            the predicate that the search will be based on.
 * @return an optional holding the found element, or an empty optional if no
 *         element was found.
 */
public Optional<E> search(Predicate<? super E> filter) {
    for (E e : characters) {
        if (e == null)
            continue;
        if (filter.test(e))
            return Optional.of(e);
    }
    return Optional.empty();
}