java.util.function.Predicate Java Examples
The following examples show how to use
java.util.function.Predicate.
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 File: ArtifactCacheBuckConfig.java From buck with Apache License 2.0 | 6 votes |
public ArtifactCacheEntries getCacheEntries() { ImmutableSet<DirCacheEntry> dirCacheEntries = getDirCacheEntries(); ImmutableSet<HttpCacheEntry> httpCacheEntries = getHttpCacheEntries(); ImmutableSet<SQLiteCacheEntry> sqliteCacheEntries = getSQLiteCacheEntries(); Predicate<DirCacheEntry> isDirCacheEntryWriteable = dirCache -> dirCache.getCacheReadMode().isWritable(); // Enforce some sanity checks on the config: // - we don't want multiple writeable dir caches pointing to the same directory dirCacheEntries.stream() .filter(isDirCacheEntryWriteable) .collect(Collectors.groupingBy(DirCacheEntry::getCacheDir)) .forEach( (path, dirCachesPerPath) -> { if (dirCachesPerPath.size() > 1) { throw new HumanReadableException( "Multiple writeable dir caches defined for path %s. This is not supported.", path); } }); return ImmutableArtifactCacheEntries.of(httpCacheEntries, dirCacheEntries, sqliteCacheEntries); }
Example #2
Source File: ReadThreadingGraph.java From gatk-protected with BSD 3-Clause "New" or "Revised" License | 6 votes |
private List<MultiDeBruijnVertex> findPath(final MultiDeBruijnVertex vertex, final int pruneFactor, final Predicate<MultiDeBruijnVertex> done, final Predicate<MultiDeBruijnVertex> returnPath, final Function<MultiDeBruijnVertex, MultiSampleEdge> nextEdge, final Function<MultiSampleEdge, MultiDeBruijnVertex> nextNode){ final LinkedList<MultiDeBruijnVertex> path = new LinkedList<>(); MultiDeBruijnVertex v = vertex; while ( ! done.test(v) ) { final MultiSampleEdge edge = nextEdge.apply(v); // if it has too low a weight, don't use it (or previous vertexes) for the path if ( edge.getPruningMultiplicity() < pruneFactor ) { path.clear(); }// otherwise it is safe to use else { path.addFirst(v); } v = nextNode.apply(edge); } path.addFirst(v); return returnPath.test(v) ? path : null; }
Example #3
Source File: ImmutableLogEntry.java From ditto with Eclipse Public License 2.0 | 6 votes |
@Override public JsonObject toJson(final JsonSchemaVersion schemaVersion, final Predicate<JsonField> predicate) { final JsonObjectBuilder builder = JsonFactory.newObjectBuilder() .set(JsonFields.CORRELATION_ID, correlationId) .set(JsonFields.TIMESTAMP, timestamp.toString()) .set(JsonFields.CATEGORY, logCategory.getName()) .set(JsonFields.TYPE, logType.getType()) .set(JsonFields.LEVEL, logLevel.getLevel()) .set(JsonFields.MESSAGE, message); if (null != address) { builder.set(JsonFields.ADDRESS, address); } if (null != thingId) { builder.set(JsonFields.THING_ID, thingId.toString()); } return builder.build(); }
Example #4
Source File: TomlBackedConfiguration.java From cava with Apache License 2.0 | 6 votes |
private <T> List<T> getList( String key, String typeName, Predicate<TomlArray> tomlCheck, Function<String, List<T>> defaultGet) { return getValue(key, keyPath -> { TomlArray array = toml.getArray(keyPath); if (array == null) { return null; } if (!tomlCheck.test(array)) { throw new InvalidConfigurationPropertyTypeException( inputPositionOf(keyPath), "List property '" + joinKeyPath(keyPath) + "' does not contain " + typeName); } @SuppressWarnings("unchecked") List<T> typedList = (List<T>) array.toList(); return typedList; }, defaultGet); }
Example #5
Source File: AppleDescriptions.java From buck with Apache License 2.0 | 6 votes |
private static BuildRuleParams getBundleParamsWithUpdatedDeps( BuildRuleParams params, BuildTarget originalBinaryTarget, Set<BuildRule> newDeps) { // Remove the unflavored binary rule and add the flavored one instead. Predicate<BuildRule> notOriginalBinaryRule = BuildRules.isBuildRuleWithTarget(originalBinaryTarget).negate(); return params .withDeclaredDeps( FluentIterable.from(params.getDeclaredDeps().get()) .filter(notOriginalBinaryRule::test) .append(newDeps) .toSortedSet(Ordering.natural())) .withExtraDeps( params.getExtraDeps().get().stream() .filter(notOriginalBinaryRule) .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural()))); }
Example #6
Source File: BlazeJavaWorkspaceImporterTest.java From intellij with Apache License 2.0 | 6 votes |
@Test public void testLibraryDepsWithJdepsReportingZeroShouldNotIncludeDirectDepsIfNotInWorkingSet() { ProjectView projectView = ProjectView.builder() .add( ListSection.builder(DirectorySection.KEY) .add(DirectoryEntry.include(new WorkspacePath("java/apps/example"))) .add(DirectoryEntry.include(new WorkspacePath("javatests/apps/example")))) .build(); TargetMapBuilder targetMapBuilder = targetMapForJdepsSuite(); workingSet = new JavaWorkingSet( workspaceRoot, new WorkingSet(ImmutableList.of(), ImmutableList.of(), ImmutableList.of()), Predicate.isEqual("BUILD")); BlazeJavaImportResult result = importWorkspace(workspaceRoot, targetMapBuilder, projectView); assertThat( result .libraries .values() .stream() .map(BlazeJavaWorkspaceImporterTest::libraryFileName) .collect(Collectors.toList())) .isEmpty(); }
Example #7
Source File: ValidatingSpliteratorTest.java From streams-utils with Apache License 2.0 | 6 votes |
@Test public void should_conform_to_specified_trySplit_behavior() { // Given Stream<String> strings = Stream.of("one", "two", "three"); Predicate<String> validator = s -> s.length() == 3; Function<String, String> transformIfValid = String::toUpperCase; Function<String, String> transformIfNotValid = s -> "-"; Stream<String> testedStream = StreamsUtils.validate(strings, validator, transformIfValid, transformIfNotValid); TryAdvanceCheckingSpliterator<String> spliterator = new TryAdvanceCheckingSpliterator<>(testedStream.spliterator()); Stream<String> monitoredStream = StreamSupport.stream(spliterator, false); // When long count = monitoredStream.count(); // Then assertThat(count).isEqualTo(3L); }
Example #8
Source File: BlazeGoAdditionalLibraryRootsProvider.java From intellij with Apache License 2.0 | 6 votes |
static ImmutableList<File> getLibraryFiles( Project project, BlazeProjectData projectData, ImportRoots importRoots) { if (!projectData.getWorkspaceLanguageSettings().isLanguageActive(LanguageClass.GO)) { return ImmutableList.of(); } WorkspaceRoot workspaceRoot = WorkspaceRoot.fromProjectSafe(project); if (workspaceRoot == null) { return ImmutableList.of(); } Predicate<File> isExternal = f -> { WorkspacePath path = workspaceRoot.workspacePathForSafe(f); return path == null || !importRoots.containsWorkspacePath(path); }; // don't use sync cache, because // 1. this is used during sync before project data is saved // 2. the roots provider is its own cache return BlazeGoPackage.getUncachedTargetToFileMap(project, projectData).values().stream() .filter(isExternal) .filter(f -> f.getName().endsWith(".go")) .distinct() .collect(toImmutableList()); }
Example #9
Source File: DefaultMessageTransponder.java From spring-boot-starter-canal with MIT License | 6 votes |
/** * get the filters predicate * * @param destination destination * @param schemaName schema * @param tableName table name * @param eventType event type * @return predicate */ @Override protected Predicate<Map.Entry<Method, ListenPoint>> getAnnotationFilter(String destination, String schemaName, String tableName, CanalEntry.EventType eventType) { Predicate<Map.Entry<Method, ListenPoint>> df = e -> StringUtils.isEmpty(e.getValue().destination()) || e.getValue().destination().equals(destination); Predicate<Map.Entry<Method, ListenPoint>> sf = e -> e.getValue().schema().length == 0 || Arrays.stream(e.getValue().schema()).anyMatch(s -> s.equals(schemaName)); Predicate<Map.Entry<Method, ListenPoint>> tf = e -> e.getValue().table().length == 0 || Arrays.stream(e.getValue().table()).anyMatch(t -> t.equals(tableName)); Predicate<Map.Entry<Method, ListenPoint>> ef = e -> e.getValue().eventType().length == 0 || Arrays.stream(e.getValue().eventType()).anyMatch(ev -> ev == eventType); return df.and(sf).and(tf).and(ef); }
Example #10
Source File: SerializedLambdaTest.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
public void testAltStdNonser() throws Throwable { MethodHandle fooMH = MethodHandles.lookup().findStatic(SerializedLambdaTest.class, "foo", predicateMT); // Alt metafactory, non-serializable target: not serializable CallSite cs = LambdaMetafactory.altMetafactory(MethodHandles.lookup(), "test", MethodType.methodType(Predicate.class), predicateMT, fooMH, stringPredicateMT, 0); assertNotSerial((Predicate<String>) cs.getTarget().invokeExact(), fooAsserter); }
Example #11
Source File: Util.java From javan-warty-pig with MIT License | 5 votes |
public static boolean checkConsecutiveBitsFlipped(byte[] bytes, Predicate<byte[]> pred) { int bitCount = bytes.length; for (int i = -1; i < bitCount; i++) { if (i >= 0) { flipBit(bytes, i); if (pred.test(bytes)) return true; } if (i < bitCount - 1) { flipBit(bytes, i + 1); if (pred.test(bytes)) return true; if (i < bitCount - 2) { flipBit(bytes, i + 2); // Only check this 3 spot if it's exactly 3 until the end if (i == bitCount - 3 && pred.test(bytes)) return true; if (i < bitCount - 3) { flipBit(bytes, i + 3); if (pred.test(bytes)) return true; flipBit(bytes, i + 3); } flipBit(bytes, i + 2); } flipBit(bytes, i + 1); } if (i >= 0) flipBit(bytes, i); } return false; }
Example #12
Source File: DirtyLambdaTest.java From training with MIT License | 5 votes |
private static <T> Matcher<T> matcher(Predicate<T> test) { return new BaseMatcher<T>() { @Override public boolean matches(Object item) { return test.test((T) item); } @Override public void describeTo(Description description) { description.appendText("Predicate test failed"); } }; }
Example #13
Source File: SerializedLambdaTest.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
public void testSerializeCapturingString() throws IOException, ClassNotFoundException { class Moo { @SuppressWarnings("unchecked") Predicate<String> foo(String t) { return (Predicate<String> & Serializable) s -> s.equals(t); } } Predicate<String> pred = new Moo().foo("goo"); assertSerial(pred, p -> { assertTrue(p.test("goo")); assertFalse(p.test("foo")); }); }
Example #14
Source File: SerializedLambdaTest.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
public void testSerializeCapturingString() throws IOException, ClassNotFoundException { class Moo { @SuppressWarnings("unchecked") Predicate<String> foo(String t) { return (Predicate<String> & Serializable) s -> s.equals(t); } } Predicate<String> pred = new Moo().foo("goo"); assertSerial(pred, p -> { assertTrue(p.test("goo")); assertFalse(p.test("foo")); }); }
Example #15
Source File: AttributeTypeRequestListProcessor.java From entando-core with GNU Lesser General Public License v3.0 | 5 votes |
@Override protected Function<Filter, Predicate<AttributeInterface>> getPredicates() { return (filter) -> { switch (filter.getAttribute()) { case KEY_CODE: return p -> FilterUtils.filterString(filter, p.getType()); default: return null; } }; }
Example #16
Source File: X509CertificateCredential.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * {@inheritDoc} */ @Override protected Predicate<String> getAuthIdValidator() { return authId -> { final X500Principal distinguishedName = new X500Principal(authId); return distinguishedName.getName(X500Principal.RFC2253).equals(authId); }; }
Example #17
Source File: FillListener.java From ProjectAres with GNU Affero General Public License v3.0 | 5 votes |
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onInventoryOpen(InventoryOpenEvent event) { final MatchPlayer opener = playerFinder.getParticipant(event.getActor()); if(opener == null) return; final Inventory inventory = event.getInventory(); final Predicate<Filter> passesFilter = passesFilter(inventory.getHolder()); if(passesFilter == null) return; logger.fine(() -> opener.getName() + " opened a " + inventory.getHolder().getClass().getSimpleName()); // Find all Fillers that apply to the holder of the opened inventory final List<Filler> fillers = this.fillers.stream() .filter(filler -> passesFilter.test(filler.filter())) .collect(Collectors.toImmutableList()); if(fillers.isEmpty()) return; logger.fine(() -> "Found fillers " + fillers.stream() .map(Filler::identify) .collect(java.util.stream.Collectors.joining(", "))); // Find all Caches that the opened inventory is part of final List<Fillable> fillables = new ArrayList<>(); for(Cache cache : caches) { if(passesFilter.test(cache.region()) && passesFilter.test(cache.filter())) { fillables.add(new FillableCache(cache)); } } // If the inventory is not in any Cache, just fill it directly if(fillables.isEmpty()) { fillables.add(new FillableInventory(inventory)); } fillables.forEach(fillable -> fillable.fill(opener, fillers)); }
Example #18
Source File: DremioHadoopFileSystemWrapper.java From dremio-oss with Apache License 2.0 | 5 votes |
@Override public DirectoryStream<FileAttributes> list(Path f, Predicate<Path> filter) throws FileNotFoundException, IOException { try (WaitRecorder recorder = OperatorStats.getWaitRecorder(operatorStats)) { return new ArrayDirectoryStream(underlyingFs.listStatus(toHadoopPath(f), toPathFilter(filter))); } catch(FSError e) { throw propagateFSError(e); } }
Example #19
Source File: ProtocolSubscriptionBuilderImpl.java From helper with MIT License | 5 votes |
@Nonnull @Override public ProtocolSubscriptionBuilder filter(@Nonnull Predicate<PacketEvent> predicate) { Objects.requireNonNull(predicate, "predicate"); this.filters.add(predicate); return this; }
Example #20
Source File: Bindables.java From Quicksql with MIT License | 5 votes |
/** * Creates a BindableProjectRule. * * @param relBuilderFactory Builder for relational expressions */ public BindableProjectRule(RelBuilderFactory relBuilderFactory) { super(LogicalProject.class, (Predicate<LogicalProject>) RelOptUtil::containsMultisetOrWindowedAgg, Convention.NONE, BindableConvention.INSTANCE, relBuilderFactory, "BindableProjectRule"); }
Example #21
Source File: UHComponents.java From lucene-solr with Apache License 2.0 | 5 votes |
public UHComponents(String field, Predicate<String> fieldMatcher, Query query, BytesRef[] terms, PhraseHelper phraseHelper, LabelledCharArrayMatcher[] automata, boolean hasUnrecognizedQueryPart, Set<UnifiedHighlighter.HighlightFlag> highlightFlags) { this.field = field; this.fieldMatcher = fieldMatcher; this.query = query; this.terms = terms; this.phraseHelper = phraseHelper; this.automata = automata; this.hasUnrecognizedQueryPart = hasUnrecognizedQueryPart; this.highlightFlags = highlightFlags; }
Example #22
Source File: FixedDefaultWorkbench.java From dsl-devkit with Eclipse Public License 1.0 | 5 votes |
/** * Close all shells matching given name predicate. * * @param predicate * condition on name of shells * @return the fixed default workbench */ FixedDefaultWorkbench closeShellsMatchingName(final Predicate<String> predicate) { SWTBotShell[] shells = bot.shells(); for (SWTBotShell shell : shells) { if (!isEclipseShell(shell) && !isLimboShell(shell) && !isQuickAccess(shell) && predicate.test(shell.getText())) { shell.close(); } } return this; }
Example #23
Source File: FeatureGuardWithPredicatesTest.java From titus-control-plane with Apache License 2.0 | 5 votes |
@Test public void testDynamicTurnOff() { AtomicBoolean turnOnRef = new AtomicBoolean(true); Predicate<String> featureGuard = FeatureGuards.toPredicate(FeatureGuards.newWhiteList() .withTurnOnPredicate(turnOnRef::get) .withWhiteListRegExpSupplier("whiteList", () -> "enabled.*") .build() ); assertThat(featureGuard.test("enabledABC")).isTrue(); turnOnRef.set(false); assertThat(featureGuard.test("enabledABC")).isFalse(); }
Example #24
Source File: OnPropertyCondition.java From joyrpc with Apache License 2.0 | 5 votes |
/** * 匹配 * * @param env 环境变量 * @param key 键 * @param matchIfMissing 不存在是否通过 * @param predicate 断言 * @return 匹配标识 */ protected boolean match(final Map<String, String> env, final String key, final boolean matchIfMissing, final Predicate<String> predicate) { //设置了值,则认为是name,其值应该是true或false String value = env.get(key); if ((value == null || value.isEmpty()) && matchIfMissing) { return true; } else { return predicate.test(value); } }
Example #25
Source File: Example1.java From clean-architecture with Apache License 2.0 | 5 votes |
public static void universalListProcessor(Function<Integer, Integer> func, Predicate<Integer> pred) { List<Integer> collection = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> col = collection.stream() .filter(pred) .map(func) .collect(Collectors.toList()); System.out.println(col); }
Example #26
Source File: TrollingIndexReaderFactory.java From lucene-solr with Apache License 2.0 | 5 votes |
public static Trap catchTrace(Predicate<StackTraceElement> judge, Runnable onCaught) { return setTrap(new Trap() { private boolean trigered; @Override protected boolean shouldExit() { Exception e = new Exception("stack sniffer"); e.fillInStackTrace(); StackTraceElement[] stackTrace = e.getStackTrace(); for(StackTraceElement trace : stackTrace) { if (judge.test(trace)) { trigered = true; recordStackTrace(stackTrace); onCaught.run(); return true; } } return false; } @Override public boolean hasCaught() { return trigered; } @Override public String toString() { return ""+judge; } }); }
Example #27
Source File: LazyFilteringSpliterator.java From cyclops with Apache License 2.0 | 5 votes |
public LazyFilteringSpliterator(final Spliterator<T> source, Supplier<Predicate<? super T>> mapperSupplier) { super(source.estimateSize(),source.characteristics() & Spliterator.ORDERED); this.source = source; this.mapperSupplier = mapperSupplier; this.mapper = mapperSupplier.get(); }
Example #28
Source File: OldObjects.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
private static Predicate<RecordedEvent> hasJavaThread(String expectedThread) { if (expectedThread != null) { return e -> e.getThread() != null && expectedThread.equals(e.getThread().getJavaName()); } else { return e -> true; } }
Example #29
Source File: Chapter04Functional.java From Java-9-Cookbook with MIT License | 5 votes |
private static Predicate<Double> createIsBiggerThan(double limit){ Predicate<Double> pred = new Predicate<Double>() { public boolean test(Double num) { System.out.println("Test if " + num + " is bigger than " + limit); return num > limit; } }; return pred; }
Example #30
Source File: MultiRepeatWhilstOp.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
public RepeatWhilstProcessor(Multi<? extends T> upstream, MultiSubscriber<? super T> downstream, long times, Predicate<T> predicate) { super(downstream); this.upstream = upstream; this.predicate = predicate; this.remaining = times; }