Java 类java.util.function.Predicate 实例源码

项目:koryphe    文件:OrTest.java   
@Test
public void shouldRejectWhenAllFunctionsReject() {
    // Given
    final Predicate<String> func1 = mock(Predicate.class);
    final Predicate<String> func2 = mock(Predicate.class);
    final Predicate<String> func3 = mock(Predicate.class);
    final Or<String> or = new Or<>(func1, func2, func3);

    given(func1.test("value")).willReturn(false);
    given(func2.test("value")).willReturn(false);
    given(func3.test("value")).willReturn(false);

    // When
    boolean accepted = or.test("value");

    // Then
    assertFalse(accepted);
    verify(func1).test("value");
    verify(func2).test("value");
    verify(func3).test("value");
}
项目:com-liferay-apio-architect    文件:FieldsWriter.java   
/**
 * Writes a {@code Map<String, S>} returned by a {@link Representor}
 * function. This method uses a consumer so each caller can decide what to
 * do with each entry. Each member of the map is filtered using the {@link
 * Fields} predicate provided by {@link #getFieldsPredicate()}.
 *
 * @param representorFunction the {@code Representor} function that returns
 *        the map being written
 * @param consumer the consumer used to process each filtered entry
 */
public <U> void writeFields(
    Function<Representor<T, S>, Map<String, U>> representorFunction,
    Consumer<Entry<String, U>> consumer) {

    Map<String, U> map = representorFunction.apply(_representor);

    Set<Entry<String, U>> entries = map.entrySet();

    Stream<Entry<String, U>> stream = entries.stream();

    stream.filter(
        entry -> {
            Predicate<String> fieldsPredicate = getFieldsPredicate();

            return fieldsPredicate.test(entry.getKey());
        }
    ).forEach(
        consumer
    );
}
项目:manifold    文件:FqnCacheNode.java   
@SuppressWarnings("UnusedDeclaration")
public final boolean visitNodeBreadthFirst( Predicate<FqnCacheNode> visitor )
{
  if( !visitor.test( this ) )
  {
    return false;
  }
  if( _children != null )
  {
    List<FqnCacheNode<K>> copy = new ArrayList<>( _children.values() );
    for( FqnCacheNode<K> child : copy )
    {
      child.visitNodeBreadthFirst( visitor );
    }
  }
  return true;
}
项目:keycloak-protocol-cas    文件:AbstractUserRoleMappingMapper.java   
/**
 * Retrieves all roles of the current user based on direct roles set to the user, its groups and their parent groups.
 * Then it recursively expands all composite roles, and restricts according to the given predicate {@code restriction}.
 * If the current client sessions is restricted (i.e. no client found in active user session has full scope allowed),
 * the final list of roles is also restricted by the client scope. Finally, the list is mapped to the token into
 * a claim.
 */
protected void setAttribute(Map<String, Object> attributes, ProtocolMapperModel mappingModel, UserSessionModel userSession,
                                   Predicate<RoleModel> restriction, String prefix) {
    String rolePrefix = prefix == null ? "" : prefix;
    UserModel user = userSession.getUser();

    // get a set of all realm roles assigned to the user or its group
    Stream<RoleModel> clientUserRoles = getAllUserRolesStream(user).filter(restriction);

    boolean dontLimitScope = userSession.getAuthenticatedClientSessions().values().stream().anyMatch(cs -> cs.getClient().isFullScopeAllowed());
    if (! dontLimitScope) {
        Set<RoleModel> clientRoles = userSession.getAuthenticatedClientSessions().values().stream()
          .flatMap(cs -> cs.getClient().getScopeMappings().stream())
          .collect(Collectors.toSet());

        clientUserRoles = clientUserRoles.filter(clientRoles::contains);
    }

    Set<String> realmRoleNames = clientUserRoles
      .map(m -> rolePrefix + m.getName())
      .collect(Collectors.toSet());

    setPlainAttribute(attributes, mappingModel, realmRoleNames);
}
项目:freecol    文件:Colony.java   
/**
 * Find a student for the specified teacher.
 * Do not search if ALLOW_STUDENT_SELECTION is true--- its the
 * player's job then.
 *
 * @param teacher The teacher {@code Unit} that needs a student.
 * @return A potential student, or null of none found.
 */
public Unit findStudent(final Unit teacher) {
    if (getSpecification().getBoolean(GameOptions.ALLOW_STUDENT_SELECTION))
        return null; // No automatic assignment
    final GoodsType expertProduction
            = teacher.getType().getExpertProduction();
    final Predicate<Unit> teacherPred = u ->
            u.getTeacher() == null && u.canBeStudent(teacher);
    // Always pick the student with the least skill first.
    // Break ties by favouring the one working in the teacher's trade,
    // otherwise first applicant wins.
    final Comparator<Unit> skillComparator
            = Comparator.comparingInt(Unit::getSkillLevel);
    final Comparator<Unit> tradeComparator
            = Comparator.comparingInt(u ->
            (u.getWorkType() == expertProduction) ? 0 : 1);
    final Comparator<Unit> fullComparator
            = skillComparator.thenComparing(tradeComparator);
    return minimize(getUnits(), teacherPred, fullComparator);
}
项目:cyberduck    文件:ListFilteringFeature.java   
protected Path search(final Path file) throws BackgroundException {
    final AttributedList<Path> list;
    if(!cache.isCached(file.getParent())) {
        list = session.list(file.getParent(), new DisabledListProgressListener());
        cache.put(file.getParent(), list);
    }
    else {
        list = cache.get(file.getParent());
    }
    final Predicate<Path> predicate;
    final Predicate<Path> simple = session.getCase() == Session.Case.insensitive ? new CaseInsensitivePathPredicate(file) : new SimplePathPredicate(file);
    if(StringUtils.isNotBlank(file.attributes().getVersionId())) {
        // Look for exact match
        return list.filter(new NullFilter<>()).find(new PredicateChain<Path>(simple, new DefaultPathPredicate(file)));
    }
    else {
        return list.filter(new NullFilter<>()).find(simple);
    }
}
项目:manifold    文件:WeakFqnCache.java   
@Override
public boolean visitBreadthFirst( final Predicate<T> visitor )
{
  Predicate<WeakReference<T>> delegate = new Predicate<WeakReference<T>>()
  {
    @Override
    public boolean test( WeakReference<T> node )
    {
      T userData = node == null ? null : node.get();
      return visitor.test( userData );
    }
  };
  List<FqnCacheNode<WeakReference<T>>> copy = new ArrayList<FqnCacheNode<WeakReference<T>>>( _cache.getChildren() );
  for( FqnCacheNode<WeakReference<T>> child : copy )
  {
    child.visitBreadthFirst( delegate );
  }
  return true;
}
项目:shuffleboard    文件:DashboardTab.java   
@Override
public boolean hasComponentFor(String sourceId) {
  List<Component> topLevelComponents = getWidgetPane().getTiles().stream()
      .map(Tile::getContent)
      .collect(Collectors.toList());
  Predicate<Sourced> isSameSource = s -> s.getSources().stream()
      .map(DataSource::getId)
      .anyMatch(sourceId::equals);
  Predicate<Sourced> isSubSource = s -> s.getSources().stream()
      .map(i -> i.getId() + "/")
      .anyMatch(sourceId::startsWith);
  Predicate<Sourced> isNotContainer = s -> !(s instanceof ComponentContainer);
  Predicate<Sourced> hasComponent = isSameSource.or(isSubSource.and(isNotContainer));
  return topLevelComponents.stream()
      .flatMap(TypeUtils.castStream(Sourced.class))
      .anyMatch(hasComponent)
      || topLevelComponents.stream()
      .flatMap(TypeUtils.castStream(ComponentContainer.class))
      .flatMap(ComponentContainer::allComponents)
      .flatMap(TypeUtils.castStream(Sourced.class))
      .anyMatch(hasComponent);
}
项目:trivor-nlp    文件:VocabularyGenerator.java   
Set<WordUsage> getSentences(List<Sentence> sentences, Function<Token, String> customMapper,
                             Predicate<String> customFilter) {
    final Map<String, Set<String>> words = new HashMap<>();
    for (Sentence sentence: sentences) {
        Stream<String> wordsStream = sentence.getTokens().stream()
                .filter(t -> t.getToken().matches(WORD_REGEX))
                .filter(t -> getTags().contains(t.getTag()))
                .filter(t -> !isUpperCase(t.getToken().charAt(0)))
                .filter(t -> t.getProb() >= config.getVocabularyProb())
                .map(customMapper);

        if (customFilter != null) {
            wordsStream = wordsStream.filter(customFilter);
        }

        wordsStream.forEach(word -> {
            final Set<String> wordSentences = words.getOrDefault(word, new HashSet<>());
            wordSentences.add(sentence.getSentence());
            words.put(word, wordSentences);
        });
    }

    return words.entrySet().stream()
            .sorted(reverseOrder(comparingInt(e -> e.getValue().size())))
            .map(e -> new WordUsage(e.getKey(), e.getValue())).collect(toSet());
}
项目:openjdk-jdk10    文件:ReferencePipeline.java   
@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);
                }
            };
        }
    };
}
项目:redirector    文件:StaticEngineBuiltFromWSModelTest.java   
@Before
public void setUp() throws Exception {
    urlRules = buildURLRules(buildDefaultStatement(PORT, PROTOCOL, URN, "4"));
    stubNamespacedListsHolder = new StubNamespacedListsHolder();
    Config config = new Config();

    ServiceProviderManagerFactory serviceProviderManagerFactory = new ServiceProviderManagerFactory();
    serviceProviderManagerFactory.setConfig(config);
    serviceProviderManagerFactory.setProviderStrategy(new RoundRobinStrategy<>());

    factory = new RedirectorEngineFactory(serviceProviderManagerFactory);

    ReflectionTestUtils.setField(factory, "config", config);
    ReflectionTestUtils.setField(factory, "isStaticDiscoveryNeededForApp", Predicate.isEqual(APP_NAME));
    ReflectionTestUtils.setField(factory, "serializer", serializer);
}
项目:openapi-parser    文件:BigParseTest.java   
@Test
public void test() throws JsonProcessingException, IOException {
    Object parsedYaml = new Yaml().load(modelUrl.openStream());
    JsonNode tree = new YAMLMapper().convertValue(parsedYaml, JsonNode.class);
    final OpenApi3 model = (OpenApi3) new OpenApiParser().parse(modelUrl, false);
    Predicate<JsonNode> valueNodePredicate = n -> n.isValueNode();

    JsonTreeWalker.WalkMethod valueChecker = new JsonTreeWalker.WalkMethod() {
        @Override
        public void run(JsonNode node, JsonPointer path) {
            IJsonOverlay<?> overlay = ((OpenApi3Impl) model).find(path);
            assertNotNull("No overlay object found for path: " + path, overlay);
            Object fromJson = getValue(node);
            String msg = String.format("Wrong overlay value for path '%s': expected '%s', got '%s'", path, fromJson,
                    overlay.get());
            assertEquals(msg, fromJson, overlay.get());
        }
    };
    JsonTreeWalker.walkTree(tree, valueNodePredicate, valueChecker);
}
项目:SoftUni    文件:p05_FilterByAge.java   
private static Predicate<Integer> createTester(String condition, Integer age) {
    // simple check the according given age
    switch(condition){
        case "younger": return x -> x < age;
        case "older": return x -> x >= age;
    }
    return null;
}
项目:openjdk-jdk10    文件:ElementStructureTest.java   
Predicate<String> constructAcceptIgnoreList(String fromFiles) throws IOException {
    StringBuilder acceptPattern = new StringBuilder();
    StringBuilder rejectPattern = new StringBuilder();
    for (String file : fromFiles.split(File.pathSeparator)) {
        try (Stream<String> lines = Files.lines(Paths.get(file))) {
            lines.forEach(line -> {
                if (line.isEmpty())
                    return;
                StringBuilder targetPattern;
                switch (line.charAt(0)) {
                    case '+':
                        targetPattern = acceptPattern;
                        break;
                    case '-':
                        targetPattern = rejectPattern;
                        break;
                    default:
                        return ;
                }
                line = line.substring(1);
                if (line.endsWith("/")) {
                    line += "[^/]*";
                } else {
                    line += "|" + line + "$[^/]*";
                }
                line = line.replace("/", ".");
                if (targetPattern.length() != 0)
                    targetPattern.append("|");
                targetPattern.append(line);
            });
        }
    }
    Pattern accept = Pattern.compile(acceptPattern.toString());
    Pattern reject = Pattern.compile(rejectPattern.toString());

    return clazzName -> accept.matcher(clazzName).matches() && !reject.matcher(clazzName).matches();
}
项目:SoftUni    文件:RepositoryFilters.java   
private Predicate<Double> createFilter(String filterType) {
    switch (filterType) {
        case "excellent":
            return mark -> mark >= 5.0;
        case "average":
            return mark -> 3.5 <= mark && mark < 5.0;
        case "poor":
            return mark -> mark < 3.5;
        default:
            return null;
    }
}
项目:javanalysis    文件:CtClassScanner.java   
public static void scanDirectory(File directory, Predicate<CtClass> predicate, Consumer<CtMethod> consumer) {
    for (String entry : directory.list()) {
        String path = directory.getPath() + File.separator + entry;
        File file = new File(path);
        if (file.isDirectory()) {
            scanDirectory(file, predicate, consumer);
        } else if (file.isFile() && path.endsWith(".class")) {
            scanClassFile(path, predicate, consumer);
        }
    }
}
项目:quickmon    文件:HealthChecksQuery.java   
public Predicate<HealthCheck> asPredicate() {
    Predicate<HealthCheck> predicate = h -> true;
    if (tags != null && !tags.isEmpty()) {
        predicate = predicate.and(h -> h.getTags().containsAll(tags));
    }
    if (status != null) {
        predicate = predicate.and(h -> h.getLastStatus().getHealth() == status);
    }
    if (luceneQuery != null) {
        HealthChecksQueryNodeInterpreter interpreter = new HealthChecksQueryNodeInterpreter();
        Predicate<HealthCheck> luceneQueryPredicate = interpreter.toPredicate(getLuceneQuery());
        predicate = predicate.and(luceneQueryPredicate);
    }
    return predicate;
}
项目:bird-java    文件:ListHelper.java   
public T firstOrDefault(Predicate<? super T> filter) {
    int size = this.items.size();
    if (size == 0) return null;

    List list = this.items;
    if (filter == null) return (T) list.get(0);

    for (int i = 0; i <= size - 1; i++) {
        T item = (T) list.get(i);
        if (filter.test(item)) {
            return item;
        }
    }
    return null;
}
项目:openjdk-jdk10    文件:PoolHelper.java   
/**
 * Gets all methods from the pool using specified filter
 *
 * @param filter method filter
 * @return pairs of Executable and appropriate Callable
 */
public List<Pair<Executable, Callable<?>>> getAllMethods(
        Predicate<Executable> filter) {
    return getAllMethods().stream()
            .filter(pair -> filter.test(pair.first))
            .collect(Collectors.toList());
}
项目:esup-ecandidat    文件:UserController.java   
/**
 * Verifie si le user est gestionnaire de candidat
 * 
 * @return true si le user est gestionnaire
 */
public Boolean isGestionnaireCandidatLS(Authentication auth) {
    if (auth == null) {
        return false;
    }
    return auth.getAuthorities().stream().map(GrantedAuthority::getAuthority)
            .filter(Predicate.isEqual(ConstanteUtils.ROLE_GESTION_CANDIDAT_LS)).findAny().isPresent();
}
项目:morpheus-core    文件:XDataFrame.java   
/**
 * Constructor
 * @param from      the from ordinal
 * @param to        the to col ordinal
 * @param predicate the predicate to match columns
 */
SelectColumns(int from, int to, Predicate<DataFrameColumn<R,C>> predicate) {
    this.from = from;
    this.to = to;
    this.predicate = predicate;
    this.threshold = Integer.MAX_VALUE;
    if (isParallel()) {
        this.threshold = DataFrameOptions.getColumnSplitThreshold(XDataFrame.this);
    }
}
项目:Biliomi    文件:FilterDirectiveQueryProcessor.java   
/**
 * Use the "filter" query parameter to filter a list of entities.
 * - Chains filter directives in order of appearance
 * - Supports filtering on sub-properties by providing the path as "Property.SubProperty".
 * - Supports basic and/or per directive against previous directives
 *
 * @param entities    The list of entities to filter
 * @param queryParams A map with the value of the "filter" query parameter
 * @return The filtered list of entities
 * @throws IOException When Jackson is unnable to unmarshal the sorting directives
 */
@Override
public List<T> process(List<T> entities, Map<String, Object> queryParams) throws Exception {
  if (entities.size() != 0 && queryParams.containsKey(PARAM_NAME_FILTER)) {
    try {
      String filter = (String) queryParams.get(PARAM_NAME_FILTER);
      Collection<RestFilterDirective> filterDirectives = null;
      // noinspection unchecked This error is inevitable depending on user input
      Class<T> rootClass = (Class<T>) entities.get(0).getClass();

      if (StringUtils.isNotEmpty(filter)) {
        if (filter.startsWith("[") && filter.endsWith("]")) {
          // This looks like a JSON-array, use Jackson to parse it
          filterDirectives = JacksonMarshaller.unmarshalCollection(filter, RestFilterDirective.class);
        } else {
          // Maybe it's a query, parse it to find out
          filterDirectives = RestFilterQueryParser.parseQuery(filter);
        }
      }

      Predicate<T> predicateChain = buildPredicateChain(filterDirectives, rootClass);
      if (predicateChain != null) {
        entities = entities.stream()
            .filter(predicateChain)
            .collect(Collectors.toList());
      }

    } catch (Exception e) {
      LogManager.getLogger(this.getClass()).error(e);
      throw e;
    }
  }

  return entities;
}
项目:FreeCol    文件:DebugUtils.java   
/**
 * Debug action to set the amount of goods in a colony.
 *
 * Called from the colony panel.
 *
 * @param freeColClient The {@code FreeColClient} for the game.
 * @param colony The {@code Colony} to set goods amounts in.
 */
public static void setColonyGoods(final FreeColClient freeColClient,
                                  final Colony colony) {
    final Specification spec = colony.getSpecification();
    final Predicate<GoodsType> goodsPred = gt ->
        !gt.isFoodType() || gt == spec.getPrimaryFoodType();
    final Function<GoodsType, ChoiceItem<GoodsType>> mapper = gt ->
        new ChoiceItem<GoodsType>(Messages.getName(gt), gt);

    GoodsType goodsType = freeColClient.getGUI().getChoice(null,
        StringTemplate.template("prompt.selectGoodsType"), "cancel",
        transform(spec.getGoodsTypeList(), goodsPred, mapper,
                  Comparator.naturalOrder()));
    if (goodsType == null) return;

    String response = freeColClient.getGUI().getInput(null,
            StringTemplate.template("prompt.selectGoodsAmount"),
            Integer.toString(colony.getGoodsCount(goodsType)),
            "ok", "cancel");
    if (response == null || response.isEmpty()) return;
    int a;
    try {
        a = Integer.parseInt(response);
    } catch (NumberFormatException nfe) {
        return;
    }

    final FreeColServer server = freeColClient.getFreeColServer();
    final Game sGame = server.getGame();
    final Specification sSpec = server.getSpecification();
    final GoodsType sGoodsType = sSpec.getGoodsType(goodsType.getId());
    GoodsContainer cgc = colony.getGoodsContainer();
    GoodsContainer sgc = sGame.getFreeColGameObject(cgc.getId(),
                                                    GoodsContainer.class);
    cgc.setAmount(goodsType, a);
    sgc.setAmount(sGoodsType, a);
}
项目:redg    文件:ReflectionUtil.java   
public static List<Field> findFields(Class<?> clazz, Predicate<Field> predicate) {
    List<Field> matchingFields = new ArrayList<>();
    Class<?> c = clazz;
    while (c != null) {
        for (Field field : c.getDeclaredFields()) {
            if (predicate.test(field)) {
                matchingFields.add(field);
            }
        }
        c = c.getSuperclass();
    }
    return matchingFields;
}
项目:FreeCol    文件:InGameController.java   
/**
 * Create the Royal Expeditionary Force player corresponding to
 * a given player that is about to rebel.
 *
 * Public for the test suite.
 *
 * FIXME: this should eventually generate changes for the REF player.
 *
 * @param serverPlayer The {@code ServerPlayer} about to rebel.
 * @return The REF player.
 */
public ServerPlayer createREFPlayer(ServerPlayer serverPlayer) {
    final Nation refNation = serverPlayer.getNation().getREFNation();
    final Monarch monarch = serverPlayer.getMonarch();
    final ServerPlayer refPlayer = getFreeColServer().makeAIPlayer(refNation);
    final Europe europe = refPlayer.getEurope();
    final Predicate<Tile> exploredPred = t ->
        ((!t.isLand() || t.isCoastland() || t.getOwner() == serverPlayer)
            && t.isExploredBy(serverPlayer));
    // Inherit rebel player knowledge of the seas, coasts, claimed
    // land but not full detailed scouting knowledge.
    Set<Tile> explore = new HashSet<>();
    getGame().getMap().forEachTile(exploredPred, t -> explore.add(t));
    refPlayer.exploreTiles(explore);

    // Trigger initial placement routine
    refPlayer.setEntryTile(null);
    // Will change, setup only
    Player.makeContact(serverPlayer, refPlayer);

    // Instantiate the REF in Europe
    Force exf = monarch.getExpeditionaryForce();
    if (!exf.prepareToBoard()) {
        logger.warning("Unable to ensure space for the REF land units.");
        // For now, do not fail completely
    }
    List<Unit> landUnits = refPlayer.createUnits(exf.getLandUnitsList(),
                                                 europe);//-vis: safe!map
    List<Unit> navalUnits = refPlayer.createUnits(exf.getNavalUnitsList(),
                                                  europe);//-vis: safe!map
    List<Unit> leftOver = refPlayer.loadShips(landUnits, navalUnits,
                                              random);//-vis: safe!map
    if (!leftOver.isEmpty()) {
        // Should not happen, make this return null one day
        logger.warning("Failed to board REF units: "
            + join(" ", transform(leftOver, alwaysTrue(),
                                  FreeColObject::getId)));
    }
    return refPlayer;
}
项目:jdk8u-jdk    文件:RegExTest.java   
private static void patternAsPredicate() throws Exception {
    Predicate<String> p = Pattern.compile("[a-z]+").asPredicate();

    if (p.test("")) {
        failCount++;
    }
    if (!p.test("word")) {
        failCount++;
    }
    if (p.test("1234")) {
        failCount++;
    }
    report("Pattern.asPredicate");
}
项目:openjdk-jdk10    文件:JMXStatusTest.java   
@BeforeMethod
public final void startTestApp() throws Exception {
    testApp = ProcessTools.startProcess(
        TEST_APP_NAME, testAppPb,
        (Predicate<String>)l->l.trim().equals("main enter")
    );
}
项目:boomer-tuner    文件:AlbumsController.java   
Predicate<Album> searchFilter(final String searchText) {
    return album -> {
        String search = searchText.toLowerCase();
        String name = album.getName().toLowerCase();
        String artist = album.getArtist().getName().toLowerCase();
        String year = String.valueOf(album.getYear());
        return name.contains(search) || artist.contains(search) || year.contains(search);
    };
}
项目:Spring-5.0-Cookbook    文件:EmployeeScheduledStreamServiceImpl.java   
@Override
public Flux<Employee> createPubAndMain() {
    Scheduler pubWorker = Schedulers.newSingle("pub-thread");
    Predicate<Employee> validAge = (e) -> {
        System.out.println("filter thread " +Thread.currentThread().getName());
        return e.getAge() > 25;
    };
    Supplier<Flux<Employee>> deferredTask = ()->{
        System.out.println("defer thread "+Thread.currentThread().getName());
        return Flux.fromIterable(employeeDaoImpl.getEmployees());
    };
    Flux<Employee> deferred = Flux.defer(deferredTask).publishOn(pubWorker).filter(validAge);
    return deferred;
}
项目:dtmlibs    文件:SerializerSet.java   
/**
 * Unregisters all {@link Predicate}s that will cause a replacement with the given replacementClass.
 * <br>
 * This may be useful if the order of checks needs to be altered or one of the default predicates needs to be
 * replaced.
 *
 * @param replacementClass The replacement class to unregister all predicates for.
 * @return this builder object.
 */
public Builder unregisterClassReplacement(@NotNull Class replacementClass) {
    Iterator<Entry<Predicate<Class<?>>, Class>> replacementsIterator = classReplacements.entrySet().iterator();
    while (replacementsIterator.hasNext()) {
        if (replacementsIterator.next().getValue().equals(replacementClass)) {
            replacementsIterator.remove();
        }
    }
    return this;
}
项目:cascade    文件:AllOfMatcher.java   
public Matcher find(Predicate<Matcher> predicate) {
    for (Matcher matcher: this) {
        if (predicate.test(matcher)) {
            return matcher;
        }
    }
    return null;
}
项目:morpheus-core    文件:DenseArrayOfInts.java   
@Override
public final Array<Integer> filter(Predicate<ArrayValue<Integer>> predicate) {
    final ArrayCursor<Integer> cursor = cursor();
    final ArrayBuilder<Integer> builder = ArrayBuilder.of(length(), type());
    for (int i=0; i<values.length; ++i) {
        cursor.moveTo(i);
        final boolean match = predicate.test(cursor);
        if (match) {
            builder.addInt(cursor.getInt());
        }
    }
    return builder.toArray();
}
项目:limberest    文件:RestService.java   
@Override
public void initialize(Request<T> request, Principal principal, Predicate<String> roleChecker)
        throws ServiceException {
    if (principal != null)
        request.setUser(principal.getName());
    request.setUserRolePredicate(roleChecker);
}
项目:NyaaCore    文件:Message.java   
public Message broadcast(MessageType type, Predicate<Player> playerFilter) {
    for (Player player : Bukkit.getOnlinePlayers()) {
        if (playerFilter.test(player)) {
            this.send(player, type);
        }
    }
    Bukkit.getConsoleSender().sendMessage(inner.toLegacyText());
    Bukkit.getConsoleSender().sendMessage("broadcast with filter:" + playerFilter.toString());
    return this;
}
项目:creacoinj    文件:TextFieldValidator.java   
public TextFieldValidator(TextInputControl control, Predicate<String> validator) {
    this.valid.set(validator.test(control.getText()));
    apply(control, valid.get());
    control.textProperty().addListener((observableValue, prev, current) -> {
        boolean nowValid = validator.test(current);
        if (nowValid == valid.get()) return;
        valid.set(nowValid);
    });
    valid.addListener(o -> apply(control, valid.get()));
}
项目:infxnity    文件:MaskBuilder.java   
public DefaultMaskCharacter(final Predicate<Character> pAllowed, final UnaryOperator<Character> pTransformation,
        final char pDefaultValue)
{
    allowed = pAllowed;
    defaultValue = pDefaultValue;
    transformation = pTransformation;
}
项目:swblocks-jbl    文件:BuilderTest.java   
@Test
public void testBuilderCreatorVerifier() {
    final Supplier mockCreator = mock(Supplier.class);
    final Predicate mockPredicate = mock(Predicate.class);
    final Function mockBuilder = mock(Function.class);
    final ArgumentCaptor intCaptor = ArgumentCaptor.forClass(Integer.class);
    final ArgumentCaptor buildCaptor = ArgumentCaptor.forClass(Integer.class);

    when(mockCreator.get()).thenReturn(1);
    when(mockPredicate.test(intCaptor.capture())).thenReturn(true);
    when(mockBuilder.apply(buildCaptor.capture())).thenReturn(3);

    final Builder testBuilder = Builder.instanceOf(mockCreator, mockPredicate, mockBuilder);
    assertNotNull(testBuilder);

    final ArgumentCaptor consumerCaptor1 = ArgumentCaptor.forClass(Integer.class);
    final ArgumentCaptor consumerCaptor2 = ArgumentCaptor.forClass(Integer.class);

    final BiConsumer mockConsumer = mock(BiConsumer.class);
    doNothing().when(mockConsumer).accept(consumerCaptor1.capture(), consumerCaptor2.capture());

    testBuilder.with(mockConsumer, 2);

    final Object result = testBuilder.build();
    assertNotNull(result);
    assertEquals(Integer.valueOf(3), result);
    assertEquals(1, intCaptor.getValue());
    verify(mockBuilder, times(1)).apply(1);
    assertEquals(1, consumerCaptor1.getValue());
    assertEquals(2, consumerCaptor2.getValue());
}
项目:redirector    文件:AnnotationScanner.java   
private static Predicate<ClassPath.ClassInfo> isClassAnnotatedByScannedAnnotations(Set<String> annotationNames) {
    return classInfo -> {
        Set<String> annotationsForClass = getAnnotationNames(classInfo.url());
        annotationsForClass.retainAll(annotationNames);
        return ! annotationsForClass.isEmpty();
    };
}
项目:SoftUni    文件:p05_FilterByAge.java   
private static void printFilteredStudents(LinkedHashMap<String, Integer> people, Predicate<Integer> tester, Consumer<Map.Entry<String, Integer>> printer) {
    // iterate all entries in the map 'people'
    for (Map.Entry<String, Integer> person :
            people.entrySet()) {
        // if they meet the criteria 'tester'
        if (tester.test(people.get(person.getKey()))) {
            // send this pair to 'printer'
            printer.accept(person);
        }
    }
}
项目:monarch    文件:MPredicateHelper.java   
/**
 * Get the correct predicate for boolean object.
 *
 * @param op the specified predicate operation
 * @param initialValue the initial value, to be checked against, for the predicate
 * @return the predicate with correct operation and specified initial value
 */
public static Predicate getPredicateForBoolean(final TypePredicateOp op,
    final Object initialValue) {
  Predicate predicate = null;
  switch ((CompareOp) op) {
    case EQUAL:
      predicate = isEqual(initialValue);
      break;
    case NOT_EQUAL:
      predicate = isNotEqual(initialValue);
      break;
  }
  return predicate;
}