Java Code Examples for java.util.function.Predicate

The following examples show how to use java.util.function.Predicate. 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: buck   Source File: AppleDescriptions.java    License: Apache License 2.0 6 votes vote down vote up
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 2
Source Project: buck   Source File: ArtifactCacheBuckConfig.java    License: Apache License 2.0 6 votes vote down vote up
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 3
Source Project: intellij   Source File: BlazeJavaWorkspaceImporterTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 4
Source Project: ditto   Source File: ImmutableLogEntry.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@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 5
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 6
Source Project: streams-utils   Source File: ValidatingSpliteratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 7
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 8
/**
 * 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 9
Source Project: cava   Source File: TomlBackedConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
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 10
Source Project: dremio-oss   Source File: DremioHadoopFileSystemWrapper.java    License: Apache License 2.0 5 votes vote down vote up
@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 11
Source Project: training   Source File: DirtyLambdaTest.java    License: MIT License 5 votes vote down vote up
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 12
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 13
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 14
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 Project: levelup-java-examples   Source File: StreamFindAndMatch.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void stream_noneMatch() {

	Predicate<HiddenObjectGame> playsGt1000 = p -> p.getTotalPlays() > 1000;
	Predicate<HiddenObjectGame> ratingGt5 = p -> p.getRating() > 5;

	boolean noneMatch = games.stream()
			.noneMatch(ratingGt5.and(playsGt1000));

	assertTrue(noneMatch);
}
 
Example 16
@Test
public void toStringFormatSingleMethod() {
	Config config = new Config();
	config.setMethods(HttpMethod.GET);
	Predicate predicate = new MethodRoutePredicateFactory().apply(config);
	assertThat(predicate.toString()).contains("Methods: [GET]");
}
 
Example 17
Source Project: javan-warty-pig   Source File: Util.java    License: MIT License 5 votes vote down vote up
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 18
Source Project: lucene-solr   Source File: UHComponents.java    License: Apache License 2.0 5 votes vote down vote up
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 19
Source Project: dsl-devkit   Source File: FixedDefaultWorkbench.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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 20
@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 21
Source Project: lucene-solr   Source File: TrollingIndexReaderFactory.java    License: Apache License 2.0 5 votes vote down vote up
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 22
Source Project: cyclops   Source File: LazyFilteringSpliterator.java    License: Apache License 2.0 5 votes vote down vote up
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 23
Source Project: smallrye-mutiny   Source File: MultiRepeatWhilstOp.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 24
Source Project: Java-9-Cookbook   Source File: Chapter04Functional.java    License: MIT License 5 votes vote down vote up
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 25
Source Project: dragonwell8_jdk   Source File: OldObjects.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 26
Source Project: clean-architecture   Source File: Example1.java    License: Apache License 2.0 5 votes vote down vote up
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 27
Source Project: joyrpc   Source File: OnPropertyCondition.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 匹配
 *
 * @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 28
Source Project: Quicksql   Source File: Bindables.java    License: MIT License 5 votes vote down vote up
/**
 * 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 29
Source Project: helper   Source File: ProtocolSubscriptionBuilderImpl.java    License: MIT License 5 votes vote down vote up
@Nonnull
@Override
public ProtocolSubscriptionBuilder filter(@Nonnull Predicate<PacketEvent> predicate) {
    Objects.requireNonNull(predicate, "predicate");
    this.filters.add(predicate);
    return this;
}
 
Example 30
@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;
        }
    };
}