java.util.function.Predicate类的使用及代码示例

x33g5p2x  于2022-01-25 转载在 其他  
字(10.1k)|赞(0)|评价(0)|浏览(188)

本文整理了Java中java.util.function.Predicate类的一些代码示例,展示了Predicate类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Predicate类的具体详情如下:
包路径:java.util.function.Predicate
类名称:Predicate

Predicate介绍

[英]Represents a predicate (boolean-valued function) of one argument.

This is a functional interface whose functional method is #test(Object).
[中]

代码示例

代码示例来源:origin: prestodb/presto

private Set<NullableValue> filterValues(Set<NullableValue> nullableValues, TpchColumn<?> column, Constraint<ColumnHandle> constraint)
{
  return nullableValues.stream()
      .filter(convertToPredicate(constraint.getSummary(), toColumnHandle(column)))
      .filter(value -> !constraint.predicate().isPresent() || constraint.predicate().get().test(ImmutableMap.of(toColumnHandle(column), value)))
      .collect(toSet());
}

代码示例来源:origin: Graylog2/graylog2-server

private void checkUnknownParameters(Map<String, ValueReference> parameters, Set<String> contentPackParameterNames) {
  final Predicate<String> containsContentPackParameter = contentPackParameterNames::contains;
  final Set<String> unknownParameters = parameters.keySet().stream()
      .filter(containsContentPackParameter.negate())
      .collect(Collectors.toSet());
  if (!unknownParameters.isEmpty()) {
    // Ignore unknown parameters for now
    LOG.debug("Unknown parameters: {}", unknownParameters);
  }
}

代码示例来源:origin: GoogleContainerTools/jib

/**
 * Adds a filter to the walked paths.
 *
 * @param pathFilter the filter. {@code pathFilter} returns {@code true} if the path should be
 *     accepted and {@code false} otherwise.
 * @return this
 */
public DirectoryWalker filter(Predicate<Path> pathFilter) {
 this.pathFilter = this.pathFilter.and(pathFilter);
 return this;
}

代码示例来源:origin: prestodb/presto

public static boolean containsType(Type type, Predicate<Type> predicate, Predicate<Type>... orPredicates)
  {
    for (Predicate<Type> orPredicate : orPredicates) {
      predicate = predicate.or(orPredicate);
    }
    if (predicate.test(type)) {
      return true;
    }

    return type.getTypeParameters().stream().anyMatch(predicate);
  }
}

代码示例来源:origin: prestodb/presto

public Set<QualifiedTablePrefix> calculatePrefixesWithTableName(
    ConnectorSession connectorSession,
    Set<QualifiedTablePrefix> prefixes,
    TupleDomain<ColumnHandle> constraint,
    Optional<Predicate<Map<ColumnHandle, NullableValue>>> predicate)
{
  Session session = ((FullConnectorSession) connectorSession).getSession();
  Optional<Set<String>> tables = filterString(constraint, TABLE_NAME_COLUMN_HANDLE);
  if (tables.isPresent()) {
    return prefixes.stream()
        .flatMap(prefix -> tables.get().stream()
            .filter(this::isLowerCase)
            .map(table -> table.toLowerCase(ENGLISH))
            .map(table -> new QualifiedObjectName(catalogName, prefix.getSchemaName().get(), table)))
        .filter(objectName -> metadata.getTableHandle(session, objectName).isPresent() || metadata.getView(session, objectName).isPresent())
        .map(QualifiedObjectName::asQualifiedTablePrefix)
        .collect(toImmutableSet());
  }
  return prefixes.stream()
      .flatMap(prefix -> Stream.concat(
          metadata.listTables(session, prefix).stream(),
          metadata.listViews(session, prefix).stream()))
      .filter(objectName -> !predicate.isPresent() || predicate.get().test(asFixedValues(objectName)))
      .map(QualifiedObjectName::asQualifiedTablePrefix)
      .collect(toImmutableSet());
}

代码示例来源:origin: jenkinsci/jenkins

@Restricted(NoExternalUse.class) // Jelly use
public List<String> getOriginalDependencyErrors() {
  Predicate<Map.Entry<String, Boolean>> p = Map.Entry::getValue;
  return dependencyErrors.entrySet().stream().filter(p.negate()).map(Map.Entry::getKey).collect(Collectors.toList());
}

代码示例来源:origin: prestodb/presto

private Set<QualifiedTablePrefix> calculatePrefixesWithSchemaName(
    ConnectorSession connectorSession,
    TupleDomain<ColumnHandle> constraint,
    Optional<Predicate<Map<ColumnHandle, NullableValue>>> predicate)
{
  Optional<Set<String>> schemas = filterString(constraint, SCHEMA_COLUMN_HANDLE);
  if (schemas.isPresent()) {
    return schemas.get().stream()
        .filter(this::isLowerCase)
        .map(schema -> new QualifiedTablePrefix(catalogName, schema))
        .collect(toImmutableSet());
  }
  Session session = ((FullConnectorSession) connectorSession).getSession();
  return metadata.listSchemaNames(session, catalogName).stream()
      .filter(schema -> !predicate.isPresent() || predicate.get().test(schemaAsFixedValues(schema)))
      .map(schema -> new QualifiedTablePrefix(catalogName, schema))
      .collect(toImmutableSet());
}

代码示例来源:origin: prestodb/presto

@Override
public Expression visitProject(ProjectNode node, Void context)
{
  // TODO: add simple algebraic solver for projection translation (right now only considers identity projections)
  Expression underlyingPredicate = node.getSource().accept(this, context);
  List<Expression> projectionEqualities = node.getAssignments().entrySet().stream()
      .filter(SYMBOL_MATCHES_EXPRESSION.negate())
      .map(ENTRY_TO_EQUALITY)
      .collect(toImmutableList());
  return pullExpressionThroughSymbols(combineConjuncts(
      ImmutableList.<Expression>builder()
          .addAll(projectionEqualities)
          .add(underlyingPredicate)
          .build()),
      node.getOutputSymbols());
}

代码示例来源:origin: apache/kafka

private <T extends Collection<TopicPartition>> T collectPartitions(Predicate<TopicPartitionState> filter, Collector<TopicPartition, ?, T> collector) {
  return assignment.stream()
      .filter(state -> filter.test(state.value()))
      .map(PartitionStates.PartitionState::topicPartition)
      .collect(collector);
}

代码示例来源:origin: spring-projects/spring-framework

private Mono<Map<String, Object>> initAttributes(ServerWebExchange exchange) {
  if (this.sessionAttributePredicate == null) {
    return EMPTY_ATTRIBUTES;
  }
  return exchange.getSession().map(session ->
      session.getAttributes().entrySet().stream()
          .filter(entry -> this.sessionAttributePredicate.test(entry.getKey()))
          .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
}

代码示例来源:origin: prestodb/presto

leftProjections.putAll(node.getLeft()
    .getOutputSymbols().stream()
    .collect(Collectors.toMap(key -> key, Symbol::toSymbolReference)));
    .collect(Collectors.toMap(key -> key, Symbol::toSymbolReference)));
ImmutableList.Builder<Expression> joinFilterBuilder = ImmutableList.builder();
for (Expression conjunct : extractConjuncts(newJoinPredicate)) {
  if (joinEqualityExpression(node.getLeft().getOutputSymbols()).test(conjunct)) {
    ComparisonExpression equality = (ComparisonExpression) conjunct;
Optional<Expression> newJoinFilter = Optional.of(combineConjuncts(joinFilterBuilder.build()));
if (newJoinFilter.get() == TRUE_LITERAL) {
  newJoinFilter = Optional.empty();
      rightSource,
      equiJoinClauses,
      ImmutableList.<Symbol>builder()
          .addAll(leftSource.getOutputSymbols())
          .addAll(rightSource.getOutputSymbols())

代码示例来源:origin: wildfly/wildfly

private Set<String> getSessions(Flag... flags) {
  Locality locality = new CacheLocality(this.cache);
  try (Stream<Key<String>> keys = this.cache.getAdvancedCache().withFlags(flags).keySet().stream()) {
    return keys.filter(this.filter.and(key -> locality.isLocal(key))).map(key -> key.getValue()).collect(Collectors.toSet());
  }
}

代码示例来源:origin: prestodb/presto

private static ListenableFuture<?> whenAllStages(Collection<SqlStageExecution> stages, Predicate<StageState> predicate)
{
  checkArgument(!stages.isEmpty(), "stages is empty");
  Set<StageId> stageIds = newConcurrentHashSet(stages.stream()
      .map(SqlStageExecution::getStageId)
      .collect(toSet()));
  SettableFuture<?> future = SettableFuture.create();
  for (SqlStageExecution stage : stages) {
    stage.addStateChangeListener(state -> {
      if (predicate.test(state) && stageIds.remove(stage.getStageId()) && stageIds.isEmpty()) {
        future.set(null);
      }
    });
  }
  return future;
}

代码示例来源:origin: prestodb/presto

private PlanNode replaceAllRecursive(PlanNode node, PlanNode nodeToReplace)
{
  node = lookup.resolve(node);
  if (where.test(node)) {
    return nodeToReplace;
  }
  if (recurseOnlyWhen.test(node)) {
    List<PlanNode> sources = node.getSources().stream()
        .map(source -> replaceAllRecursive(source, nodeToReplace))
        .collect(toImmutableList());
    return replaceChildren(node, sources);
  }
  return node;
}

代码示例来源:origin: google/bundletool

private ImmutableSet<ModuleSplit> subsetWithTargeting(
  ImmutableList<ModuleSplit> splits, Predicate<ApkTargeting> predicate) {
 return splits.stream()
   .filter(split -> predicate.test(split.getApkTargeting()))
   .filter(split -> deviceSpec.map(spec -> splitMatchesDeviceSpec(split, spec)).orElse(true))
   .collect(toImmutableSet());
}

代码示例来源:origin: dropwizard/dropwizard

/**
 * Discards any cached role associations for principals satisfying
 * the given predicate.
 *
 * @param predicate a predicate to filter credentials
 */
public void invalidateAll(Predicate<? super P> predicate) {
  final Set<ImmutablePair<P, String>> keys = cache.asMap().keySet().stream()
      .filter(cacheKey -> predicate.test(cacheKey.getLeft()))
      .collect(Collectors.toSet());
  cache.invalidateAll(keys);
}

代码示例来源:origin: google/bundletool

/** Removes XML elements among the direct children that satisfies the given predicate. */
 public XmlProtoElementBuilder removeChildrenElementsIf(Predicate<XmlProtoNodeBuilder> filter) {
  ImmutableList<XmlNode> keptChildren =
    getChildren()
      .filter(filter.negate())
      .map(builder -> builder.build().getProto())
      .collect(toImmutableList());
  if (getProtoChildrenList().size() != keptChildren.size()) {
   element.clearChild().addAllChild(keptChildren);
  }
  return this;
 }
}

代码示例来源:origin: AxonFramework/AxonFramework

@SuppressWarnings("unchecked")
private <U> void doEmit(Predicate<SubscriptionQueryMessage<?, ?, U>> filter,
            SubscriptionQueryUpdateMessage<U> update) {
  updateHandlers.keySet()
         .stream()
         .filter(sqm -> filter.test((SubscriptionQueryMessage<?, ?, U>) sqm))
         .forEach(query -> Optional.ofNullable(updateHandlers.get(query))
                      .ifPresent(uh -> doEmit(query, uh, update)));
}

代码示例来源:origin: GoogleContainerTools/jib

/** Returns the first entry matching the given key predicate. */
@Nullable
private static <K, T> Map.Entry<K, T> findFirstInMapByKey(Map<K, T> map, Predicate<K> keyMatch) {
 return map.entrySet()
   .stream()
   .filter(entry -> keyMatch.test(entry.getKey()))
   .findFirst()
   .orElse(null);
}

代码示例来源:origin: jooby-project/jooby

public static Predicate<MethodInsnNode> param(final ClassLoader loader) {
 return is(MethodInsnNode.class).and(m -> {
  Signature signature = new Signature(loader, m);
  return PARAMS.stream()
    .filter(signature::matches)
    .findFirst()
    .isPresent();
 });
}

相关文章