java.util.stream.Stream#anyMatch ( )源码实例Demo

下面列出了java.util.stream.Stream#anyMatch ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: nifi-config   文件: CreateRouteService.java
private boolean connectionExists(
        final Stream<ConnectionEntity> connectionEntities,
        final ConnectionEntity connectionEntity) {
  return connectionEntities.anyMatch(item ->
          item.getComponent().getSource().getGroupId().equals(
                  connectionEntity.getComponent().getSource().getGroupId())
                  && item.getComponent().getSource().getId().equals(
                  connectionEntity.getComponent().getSource().getId())
                  && item.getComponent().getSource().getName().trim().equals(
                  connectionEntity.getComponent().getSource().getName().trim())
                  && item.getComponent().getSource().getType().equals(
                  connectionEntity.getComponent().getSource().getType())
                  && item.getComponent().getDestination().getGroupId().equals(
                  connectionEntity.getComponent().getDestination().getGroupId())
                  && item.getComponent().getDestination().getId().equals(
                  connectionEntity.getComponent().getDestination().getId())
                  && item.getComponent().getDestination().getName().trim().equals(
                  connectionEntity.getComponent().getDestination().getName().trim())
                  && item.getComponent().getDestination().getType().equals(
                  connectionEntity.getComponent().getDestination().getType())
  );
}
 
/**
 * Check if any entry has a prefix among the paths in the proof entries. Both found and absent
 * keys are checked.
 */
private boolean prefixesIncluded() {
  Stream<DbKey> requestedKeys =
      Stream.concat(
          entries.stream()
              .map(MapEntry::getKey),
          missingKeys.stream())
      .map(DbKey::newLeafKey);

  // TODO: proof entries are checked to be sorted at this stage, so it's possible
  //   to use binary search here
  return requestedKeys
      .anyMatch(leafEntryKey -> proof.stream()
          .map(MapProofEntry::getDbKey)
          .anyMatch(proofEntryKey ->
              proofEntryKey.isPrefixOf(leafEntryKey))
      );
}
 
源代码3 项目: hkxpack   文件: DirWalker.java
/**
 * Recursive walk function
 * @param directory the current directory {@link File} 
 * @param accumulatedPath the accumulated path of the directory
 * @param outputFiles the files detected by the walk
 */
private void walk(final File directory, final String accumulatedPath, final List<Entry> outputFiles) {
	try {
		DirectoryStream<Path> files = Files.newDirectoryStream(directory.toPath());
		for(Path directoryComponent : files) {
			File element = createFile(directoryComponent);
			if(element.isFile()) {
				Stream<String> extensionStream = Arrays.stream(extensions);
				if(extensionStream.anyMatch(
						(ext) -> {
							return directoryComponent.getFileName().toString().endsWith(ext);
						})) {
					outputFiles.add(createEntry(accumulatedPath, element));
				}
				extensionStream.close();
			}
			else if(element.isDirectory()) {
				walk(element, accumulatedPath + "/" + element.getName(), outputFiles);
			}
		}
	} catch (IOException e) {
		LOGGER.throwing(this.getClass().getName(), "walk", e);
	}
}
 
@Redirect(method = "tick", at = @At(
        value = "INVOKE",
        target = "Ljava/util/stream/Stream;noneMatch(Ljava/util/function/Predicate;)Z"
))
private boolean noneMatchSleep(Stream<ServerPlayerEntity> stream, Predicate<ServerPlayerEntity> predicate)
{
    if (CarpetSettings.onePlayerSleeping)
        return stream.anyMatch((p) -> !p.isSpectator() && p.isSleepingLongEnough());
    return stream.noneMatch(predicate);
}
 
源代码5 项目: lams   文件: AbstractSchemaMigrator.java
/**
 * Check if the ForeignKey already exists. First check based on definition and if that is not matched check if a key
 * with the exact same name exists. Keys with the same name are presumed to be functional equal.
 * 
 * @param foreignKey - ForeignKey, new key to be created
 * @param tableInformation - TableInformation, information of existing keys
 * @return boolean, true if key already exists
 */
private boolean checkForExistingForeignKey(ForeignKey foreignKey, TableInformation tableInformation) {
	if ( foreignKey.getName() == null || tableInformation == null ) {
		return false;
	}

	final String referencingColumn = foreignKey.getColumn( 0 ).getName();
	final String referencedTable = foreignKey.getReferencedTable().getName();

	/*
	 * Find existing keys based on referencing column and referencedTable. "referencedColumnName" is not checked
	 * because that always is the primary key of the "referencedTable".
	 */
	Predicate<ColumnReferenceMapping> mappingPredicate = m -> {
		String existingReferencingColumn = m.getReferencingColumnMetadata().getColumnIdentifier().getText();
		String existingReferencedTable = m.getReferencedColumnMetadata().getContainingTableInformation().getName().getTableName().getCanonicalName();
		return referencingColumn.equals( existingReferencingColumn ) && referencedTable.equals( existingReferencedTable );
	};
	Stream<ForeignKeyInformation> keyStream = StreamSupport.stream( tableInformation.getForeignKeys().spliterator(), false );
	Stream<ColumnReferenceMapping> mappingStream = keyStream.flatMap( k -> StreamSupport.stream( k.getColumnReferenceMappings().spliterator(), false ) );
	boolean found = mappingStream.anyMatch( mappingPredicate );
	if ( found ) {
		return true;
	}

	// And at the end just compare the name of the key. If a key with the same name exists we assume the function is
	// also the same...
	return tableInformation.getForeignKey( Identifier.toIdentifier( foreignKey.getName() ) ) != null;
}
 
源代码6 项目: baleen   文件: MentionDetector.java
private List<WordToken> identifyHeadCandidates(List<WordToken> words) {
  final List<WordToken> candidates = new LinkedList<>();

  for (final WordToken word : words) {
    if (word.getPartOfSpeech().startsWith("N")) {
      final Stream<WordToken> edges = dependencyGraph.getEdges(word);
      if (edges.anyMatch(p -> !words.contains(p))) {
        candidates.add(word);
      }
    }
  }

  return candidates;
}
 
源代码7 项目: java8-tutorial   文件: Streams5.java
private static void test7(List<String> stringCollection) {
    Stream<String> stream = stringCollection
        .stream()
        .filter(s -> s.startsWith("a"));

    stream.anyMatch(s -> true);
    stream.noneMatch(s -> true);
}
 
private static boolean matches(Path candidate, Stream<PathMatcher> matchers) {
    return matchers.anyMatch((m) -> (m.matches(candidate)));
}
 
源代码9 项目: helidon-build-tools   文件: SnakeYAMLMojo.java
private static boolean matches(Path candidate, Stream<PathMatcher> matchers) {
    return matchers.anyMatch((m) -> (m.matches(candidate)));
}
 
源代码10 项目: javacore   文件: Streams5.java
private static void test7(List<String> stringCollection) {
    Stream<String> stream = stringCollection.stream().filter(s -> s.startsWith("a"));

    stream.anyMatch(s -> true);
    stream.noneMatch(s -> true);
}
 
源代码11 项目: taskana   文件: WorkbasketServiceImpl.java
@Override
public WorkbasketAccessItem createWorkbasketAccessItem(WorkbasketAccessItem workbasketAccessItem)
    throws InvalidArgumentException, NotAuthorizedException, WorkbasketNotFoundException,
        WorkbasketAccessItemAlreadyExistException {
  LOGGER.debug(
      "entry to createWorkbasketAccessItemn(workbasketAccessItem = {})", workbasketAccessItem);
  taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN);
  WorkbasketAccessItemImpl accessItem = (WorkbasketAccessItemImpl) workbasketAccessItem;
  try {
    taskanaEngine.openConnection();
    accessItem.setId(IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_AUTHORIZATION));
    if (workbasketAccessItem.getId() == null
        || workbasketAccessItem.getAccessId() == null
        || workbasketAccessItem.getWorkbasketId() == null) {
      throw new InvalidArgumentException(
          String.format(
              "Checking the preconditions of the current "
                  + "WorkbasketAccessItem failed. WorkbasketAccessItem=%s",
              workbasketAccessItem));
    }
    WorkbasketImpl wb = workbasketMapper.findById(workbasketAccessItem.getWorkbasketId());
    if (wb == null) {
      throw new WorkbasketNotFoundException(
          workbasketAccessItem.getWorkbasketId(),
          String.format(
              "WorkbasketAccessItem %s refers to a not existing workbasket",
              workbasketAccessItem));
    }
    try {
      workbasketAccessMapper.insert(accessItem);
      LOGGER.debug(
          "Method createWorkbasketAccessItem() created workbaskteAccessItem {}", accessItem);
    } catch (PersistenceException e) {
      LOGGER.debug(
          "when trying to insert WorkbasketAccessItem {} caught exception", accessItem, e);
      Stream<String> accessItemExistsIdentifier =
          Stream.of(
              "SQLCODE=-803", // DB2
              "uc_accessid_wbid", // POSTGRES
              "UC_ACCESSID_WBID_INDEX_E" // H2
              );
      if (accessItemExistsIdentifier.anyMatch(e.getMessage()::contains)) {
        throw new WorkbasketAccessItemAlreadyExistException(accessItem);
      }
      throw e;
    }
    return accessItem;
  } finally {
    taskanaEngine.returnConnection();
    LOGGER.debug(
        "exit from createWorkbasketAccessItem(workbasketAccessItem). Returning result {}",
        accessItem);
  }
}
 
源代码12 项目: flutter-intellij   文件: CollectionUtils.java
public static <T> boolean anyMatch(@NotNull final Stream<T> in, @NotNull final Predicate<T> predicate) {
  return in.anyMatch(predicate);
}
 
源代码13 项目: flutter-intellij   文件: CollectionUtils.java
public static <T> boolean anyMatch(@NotNull final Stream<T> in, @NotNull final Predicate<T> predicate) {
  return in.anyMatch(predicate);
}
 
源代码14 项目: vespa   文件: FeedResponse.java
private static boolean containsFatalErrors(Stream<Error> errors) {
    return errors.anyMatch(e -> e.getCode() != DocumentProtocol.ERROR_TEST_AND_SET_CONDITION_FAILED);
}
 
源代码15 项目: revapi   文件: AbstractIncludeExcludeFilter.java
@SuppressWarnings("ConstantConditions")
private boolean decide(@Nullable Object element) {
    //we don't exclude anything that we don't handle...
    if (doNothing || !(element instanceof JavaElement)) {
        return true;
    }

    InclusionState ret = elementResults.get(element);
    if (ret != null) {
        return ret.toBoolean();
    }

    JavaElement el = (JavaElement) element;

    //exploit the fact that parent elements are always filtered before the children
    Element parent = el.getParent();
    InclusionState parentInclusionState = parent == null ? InclusionState.UNDECIDED
            : elementResults.get(parent);

    //if we have no record of the parent inclusion, then this is a top-level class. Assume it wants to be included.
    if (parentInclusionState == null) {
        parentInclusionState = InclusionState.UNDECIDED;
    }

    //this is a java element, but not a model-based element - i.e. this is an annotation.
    if (!(element instanceof JavaModelElement)) {
        return decideAnnotation((JavaAnnotationElement) element, parentInclusionState);
    }

    JavaModelElement javaElement = (JavaModelElement) element;

    Stream<String> tested = getTestedElementRepresentations(javaElement);

    //let's first assume we're going to inherit the parent's inclusion state
    ret = parentInclusionState;

    //now see if we need to change that assumption
    switch (parentInclusionState) {
    case INCLUDED:
        //the parent was explicitly included in the results. We therefore only need to check if the annotations
        //on this element should be excluded
        if (excludeTest != null) {
            if (tested.anyMatch(s -> excludeTest.test(s))) {
                ret = InclusionState.EXCLUDED;
            }
        }
        break;
    case EXCLUDED:
        if (!canBeReIncluded(javaElement)) {
            break;
        }
        //the child element can be re-included, so the full suite of tests need to be run.
        //i.e. this fall-through is intentional.
    case UNDECIDED:
        //ok, the parent is undecided. This means we have to do the full checks on this element.
        List<String> testedList = null;
        if (includeTest != null && excludeTest != null) {
            testedList = tested.collect(toList());
            tested = testedList.stream();
        }

        if (includeTest != null) {
            //ok, there is an include test but the parent is undecided. This means that the parent actually
            //didn't match the include test. Let's check with this element.
            ret = tested.anyMatch(s -> includeTest.test(s))
                    ? InclusionState.INCLUDED
                    : InclusionState.EXCLUDED;
        }

        if (excludeTest != null) {
            if (testedList != null) {
                tested = testedList.stream();
            }

            //there is an exclude test but the parent is undecided. This means that the exclude check didn't
            //match the parent. Let's check again with this element.

            if (tested.anyMatch(s -> excludeTest.test(s))) {
                ret = InclusionState.EXCLUDED;
            }
        }
        break;
    }

    elementResults.put(element, ret);
    return ret.toBoolean();
}
 
源代码16 项目: selenium   文件: IgnoreComparator.java
private boolean shouldIgnore(Stream<Ignore> ignoreList) {
  return ignoreList.anyMatch(driver ->
      (ignored.contains(driver.value()) || driver.value() == Browser.ALL)
      && (!driver.travis() || TestUtilities.isOnTravis())
      && isOpen(driver.issue()));
}
 
源代码17 项目: selenium   文件: JUnit4TestBase.java
private boolean notImplemented(Stream<NotYetImplemented> nyi) {
  return nyi.anyMatch(driver -> matches(current, new Browser[]{driver.value()}));
}
 
源代码18 项目: immutables   文件: ExpressionInterpreter.java
private static Object binaryCall(Call call, Object left, Object right) {
  Preconditions.checkArgument(call.operator().arity() == Operator.Arity.BINARY, "Expected binary call got %s", call);
  final Operator op = call.operator();

  if (op == Operators.EQUAL || op == Operators.NOT_EQUAL) {
    final boolean equals = Objects.equals(left, right);
    return (op == Operators.EQUAL) == equals;
  }

  if (op == Operators.IN || op == Operators.NOT_IN) {
    Preconditions.checkArgument(right instanceof Iterable, "%s is not iterable", left.getClass());
    @SuppressWarnings("unchecked")
    final Iterable<Object> rightValue = (Iterable<Object>) right;
    final Stream<Object> stream = StreamSupport.stream(rightValue.spliterator(), false);
    return op == Operators.IN ? stream.anyMatch(r -> Objects.equals(left, r)) : stream.noneMatch(r -> Objects.equals(left, r));
  }

  if (op == IterableOperators.HAS_SIZE) {
    Preconditions.checkArgument(left instanceof Iterable, "%s is not iterable", left);
    Preconditions.checkArgument(right instanceof Number, "%s is not a number", left);
    final Iterable<?> iter = (Iterable<?>) left;
    final int size = ((Number) right).intValue();
    return Iterables.size(iter) == size;
  }

  if (op == IterableOperators.CONTAINS) {
    Preconditions.checkArgument(left instanceof Iterable, "%s is not iterable", left);
    return Iterables.contains((Iterable<?>) left, right);
  }

  // comparables
  if (ComparableOperators.isComparable(call.operator())) {
    Preconditions.checkArgument(left instanceof Comparable, "%s is not comparable", left);
    @SuppressWarnings("unchecked")
    final Comparable<Object> leftComparable = (Comparable<Object>) left;

    Preconditions.checkArgument(right instanceof Comparable, "%s is not comparable", right);
    @SuppressWarnings("unchecked")
    final Comparable<Object> rightComparable = (Comparable<Object>) right;

    final int compare = leftComparable.compareTo(rightComparable);

    if (op == ComparableOperators.GREATER_THAN) {
      return compare > 0;
    } else if (op == ComparableOperators.GREATER_THAN_OR_EQUAL) {
      return compare >= 0;
    } else if (op == ComparableOperators.LESS_THAN) {
      return compare < 0;
    } else if (op == ComparableOperators.LESS_THAN_OR_EQUAL) {
      return compare <= 0;
    }
  }

  if (op == StringOperators.HAS_LENGTH) {
    Preconditions.checkArgument(left instanceof CharSequence, "%s is not CharSequence", left);
    Preconditions.checkArgument(right instanceof Number, "%s is not Number", right);
    int length = ((Number) right).intValue();
    return left.toString().length() == length;
  }

  if (op == StringOperators.MATCHES) {
    Preconditions.checkArgument(left instanceof CharSequence, "%s is not string (or CharSequence)", left);
    Preconditions.checkArgument(right instanceof Pattern, "%s is not regex pattern", right);
    return ((Pattern) right).asPredicate().test(left.toString());
  }

  if (op == StringOperators.STARTS_WITH || op == StringOperators.ENDS_WITH || op == StringOperators.CONTAINS) {
    Preconditions.checkArgument(left instanceof CharSequence, "%s is not string (or CharSequence)", left);
    Preconditions.checkArgument(right instanceof CharSequence, "%s is not string (or CharSequence)", right);

    if (op == StringOperators.CONTAINS) {
      return left.toString().contains(right.toString());
    }

    return op == StringOperators.STARTS_WITH ? left.toString().startsWith(right.toString()) : left.toString().endsWith(right.toString());
  }

  throw new UnsupportedOperationException("Unsupported binary call " + call);
}
 
源代码19 项目: arctic-sea   文件: Optionals.java
/**
 * Checks if any of the optionals is present.
 *
 * @param optionals the optionals
 *
 * @return if at least one is present
 */
public static boolean any(Stream<Optional<?>> optionals) {
    return optionals.anyMatch(Optional::isPresent);
}
 
源代码20 项目: freecol   文件: CollectionUtils.java
/**
 * Implementation of any().
 *
 * @param <T> The stream member type.
 * @param stream The {@code Stream} to test.
 * @param predicate The {@code Predicate} to test with.
 * @return True if any member passes the predicate test.
 */
private static <T> boolean any_internal(Stream<T> stream,
                                        Predicate<? super T> predicate) {
    return stream.anyMatch(predicate);
}