Java Code Examples for java.util.stream.Stream#anyMatch()

The following examples show how to use java.util.stream.Stream#anyMatch() . These examples are extracted from open source projects. 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 Project: nifi-config   File: CreateRouteService.java    License: Apache License 2.0 6 votes vote down vote up
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())
  );
}
 
Example 2
/**
 * 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))
      );
}
 
Example 3
Source Project: hkxpack   File: DirWalker.java    License: MIT License 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 4
@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);
}
 
Example 5
/**
 * 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;
}
 
Example 6
Source Project: baleen   File: MentionDetector.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 7
Source Project: java8-tutorial   File: Streams5.java    License: MIT License 5 votes vote down vote up
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);
}
 
Example 8
private static boolean matches(Path candidate, Stream<PathMatcher> matchers) {
    return matchers.anyMatch((m) -> (m.matches(candidate)));
}
 
Example 9
private static boolean matches(Path candidate, Stream<PathMatcher> matchers) {
    return matchers.anyMatch((m) -> (m.matches(candidate)));
}
 
Example 10
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);
}
 
Example 11
Source Project: taskana   File: WorkbasketServiceImpl.java    License: Apache License 2.0 4 votes vote down vote up
@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);
  }
}
 
Example 12
public static <T> boolean anyMatch(@NotNull final Stream<T> in, @NotNull final Predicate<T> predicate) {
  return in.anyMatch(predicate);
}
 
Example 13
public static <T> boolean anyMatch(@NotNull final Stream<T> in, @NotNull final Predicate<T> predicate) {
  return in.anyMatch(predicate);
}
 
Example 14
Source Project: vespa   File: FeedResponse.java    License: Apache License 2.0 4 votes vote down vote up
private static boolean containsFatalErrors(Stream<Error> errors) {
    return errors.anyMatch(e -> e.getCode() != DocumentProtocol.ERROR_TEST_AND_SET_CONDITION_FAILED);
}
 
Example 15
@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();
}
 
Example 16
Source Project: selenium   File: IgnoreComparator.java    License: Apache License 2.0 4 votes vote down vote up
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()));
}
 
Example 17
Source Project: selenium   File: JUnit4TestBase.java    License: Apache License 2.0 4 votes vote down vote up
private boolean notImplemented(Stream<NotYetImplemented> nyi) {
  return nyi.anyMatch(driver -> matches(current, new Browser[]{driver.value()}));
}
 
Example 18
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);
}
 
Example 19
Source Project: arctic-sea   File: Optionals.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 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);
}
 
Example 20
/**
 * 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);
}