本文整理汇总了Java中java.util.function.Predicate类的典型用法代码示例。如果您正苦于以下问题:Java Predicate类的具体用法?Java Predicate怎么用?Java Predicate使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Predicate类属于java.util.function包,在下文中一共展示了Predicate类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: shouldRejectWhenAllFunctionsReject
import java.util.function.Predicate; //导入依赖的package包/类
@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");
}
示例2: writeFields
import java.util.function.Predicate; //导入依赖的package包/类
/**
* 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
);
}
示例3: visitNodeBreadthFirst
import java.util.function.Predicate; //导入依赖的package包/类
@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;
}
示例4: setAttribute
import java.util.function.Predicate; //导入依赖的package包/类
/**
* 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);
}
示例5: findStudent
import java.util.function.Predicate; //导入依赖的package包/类
/**
* 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);
}
示例6: search
import java.util.function.Predicate; //导入依赖的package包/类
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);
}
}
示例7: visitBreadthFirst
import java.util.function.Predicate; //导入依赖的package包/类
@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;
}
示例8: hasComponentFor
import java.util.function.Predicate; //导入依赖的package包/类
@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);
}
示例9: getSentences
import java.util.function.Predicate; //导入依赖的package包/类
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());
}
示例10: filter
import java.util.function.Predicate; //导入依赖的package包/类
@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);
}
};
}
};
}
示例11: setUp
import java.util.function.Predicate; //导入依赖的package包/类
@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);
}
示例12: test
import java.util.function.Predicate; //导入依赖的package包/类
@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);
}
示例13: createTester
import java.util.function.Predicate; //导入依赖的package包/类
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;
}
示例14: constructAcceptIgnoreList
import java.util.function.Predicate; //导入依赖的package包/类
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();
}
示例15: createFilter
import java.util.function.Predicate; //导入依赖的package包/类
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;
}
}