类java.util.function.BiPredicate源码实例Demo

下面列出了怎么用java.util.function.BiPredicate的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: sailfish-core   文件: HelpContentHolder.java
private Optional<TreeNode> findNode(List<TreeNode> root, boolean recursive, BiPredicate<TreeNode, HelpJsonContainer> filter) {
    for (TreeNode node : ObjectUtils.defaultIfNull(root, Collections.<TreeNode>emptyList())) {
        HelpJsonContainer data = getContainer(node);
        if (data == null) {
            continue;
        }
        if (filter.test(node, data)) {
            return Optional.of(node);
        }
        if (recursive && CollectionUtils.isNotEmpty(node.getChildren())) {
            Optional<TreeNode> treeNode = findNode(node.getChildren(), true, filter);
            if (treeNode.isPresent()) {
                return treeNode;
            }
        }
    }
    return Optional.empty();
}
 
源代码2 项目: fastjgame   文件: CollectionUtils.java
/**
 * 移除map中符合条件的元素,并对删除的元素执行后续的操作
 *
 * @param map       必须是可修改的map
 * @param predicate 过滤条件,为真的删除
 * @param then      元素删除之后执行的逻辑
 * @param <K>       the type of key
 * @param <V>       the type of value
 * @return 删除的元素数量
 */
public static <K, V> int removeIfAndThen(final Map<K, V> map, final BiPredicate<? super K, ? super V> predicate, BiConsumer<K, V> then) {
    if (map.size() == 0) {
        return 0;
    }

    int removeNum = 0;
    // entry在调用remove之后不可再访问,因此需要将key-value保存下来
    Map.Entry<K, V> kvEntry;
    K k;
    V v;
    Iterator<Map.Entry<K, V>> itr = map.entrySet().iterator();
    while (itr.hasNext()) {
        kvEntry = itr.next();
        k = kvEntry.getKey();
        v = kvEntry.getValue();

        if (predicate.test(k, v)) {
            itr.remove();
            removeNum++;
            then.accept(k, v);
        }
    }
    return removeNum;
}
 
源代码3 项目: openjdk-jdk9   文件: Types.java
/**
 * Form the union of two closures
 */
public List<Type> union(List<Type> cl1, List<Type> cl2, BiPredicate<Type, Type> shouldSkip) {
    if (cl1.isEmpty()) {
        return cl2;
    } else if (cl2.isEmpty()) {
        return cl1;
    } else if (shouldSkip.test(cl1.head, cl2.head)) {
        return union(cl1.tail, cl2.tail, shouldSkip).prepend(cl1.head);
    } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
        return union(cl1.tail, cl2, shouldSkip).prepend(cl1.head);
    } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
        return union(cl1, cl2.tail, shouldSkip).prepend(cl2.head);
    } else {
        // unrelated types
        return union(cl1.tail, cl2, shouldSkip).prepend(cl1.head);
    }
}
 
源代码4 项目: jolie   文件: OOITBuilder.java
public void visit( CompareConditionNode n ) {
	n.leftExpression().accept( this );
	Expression left = currExpression;
	n.rightExpression().accept( this );
	Scanner.TokenType opType = n.opType();

	final BiPredicate< Value, Value > operator =
		opType == Scanner.TokenType.EQUAL ? CompareOperators.EQUAL
			: opType == Scanner.TokenType.NOT_EQUAL ? CompareOperators.NOT_EQUAL
				: opType == Scanner.TokenType.LANGLE ? CompareOperators.MINOR
					: opType == Scanner.TokenType.RANGLE ? CompareOperators.MAJOR
						: opType == Scanner.TokenType.MINOR_OR_EQUAL ? CompareOperators.MINOR_OR_EQUAL
							: opType == Scanner.TokenType.MAJOR_OR_EQUAL ? CompareOperators.MAJOR_OR_EQUAL
								: null;
	Objects.requireNonNull( operator );
	currExpression = new CompareCondition( left, currExpression, operator );
}
 
源代码5 项目: spring-analysis-note   文件: AnnotationsScanner.java
@Nullable
private static <C, R> R processMethod(C context, Method source,
		SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor,
		@Nullable BiPredicate<C, Class<?>> classFilter) {

	switch (searchStrategy) {
		case DIRECT:
		case INHERITED_ANNOTATIONS:
			return processMethodInheritedAnnotations(context, source, processor, classFilter);
		case SUPERCLASS:
			return processMethodHierarchy(context, new int[] {0}, source.getDeclaringClass(),
					processor, classFilter, source, false);
		case EXHAUSTIVE:
			return processMethodHierarchy(context, new int[] {0}, source.getDeclaringClass(),
					processor, classFilter, source, true);
	}
	throw new IllegalStateException("Unsupported search strategy " + searchStrategy);
}
 
源代码6 项目: reactor-core   文件: FluxJoin.java
@SuppressWarnings("unchecked")
JoinSubscription(CoreSubscriber<? super R> actual,
		Function<? super TLeft, ? extends Publisher<TLeftEnd>> leftEnd,
		Function<? super TRight, ? extends Publisher<TRightEnd>> rightEnd,
		BiFunction<? super TLeft, ? super TRight, ? extends R> resultSelector) {
	this.actual = actual;
	this.cancellations = Disposables.composite();
	this.queue = Queues.unboundedMultiproducer().get();
	this.queueBiOffer = (BiPredicate) queue;
	this.lefts = new LinkedHashMap<>();
	this.rights = new LinkedHashMap<>();
	this.leftEnd = leftEnd;
	this.rightEnd = rightEnd;
	this.resultSelector = resultSelector;
	ACTIVE.lazySet(this, 2);
}
 
/**
 * Starts the development server.
 *
 * @param mode the launch mode (see ILaunchManager.*_MODE constants)
 */
void startDevServer(String mode, RunConfiguration devServerRunConfiguration,
    Path javaHomePath, MessageConsoleStream outputStream, MessageConsoleStream errorStream)
    throws CoreException, CloudSdkNotFoundException {

  BiPredicate<InetAddress, Integer> portInUse = (addr, port) -> {
    Preconditions.checkArgument(port >= 0, "invalid port");
    return SocketUtil.isPortInUse(addr, port);
  };

  checkPorts(devServerRunConfiguration, portInUse);

  setServerState(IServer.STATE_STARTING);
  setMode(mode);

  // Create dev app server instance
  initializeDevServer(outputStream, errorStream, javaHomePath);

  // Run server
  try {
    devServer.run(devServerRunConfiguration);
  } catch (AppEngineException ex) {
    Activator.logError("Error starting server: " + ex.getMessage()); //$NON-NLS-1$
    stop(true);
  }
}
 
源代码8 项目: servicetalk   文件: CopyOnWriteAsyncContextMap.java
@Nullable
@Override
public Key<?> forEach(final BiPredicate<Key<?>, Object> consumer) {
    if (!consumer.test(keyOne, valueOne)) {
        return keyOne;
    }
    if (!consumer.test(keyTwo, valueTwo)) {
        return keyTwo;
    }
    if (!consumer.test(keyThree, valueThree)) {
        return keyThree;
    }
    if (!consumer.test(keyFour, valueFour)) {
        return keyFour;
    }
    if (!consumer.test(keyFive, valueFive)) {
        return keyFive;
    }
    return consumer.test(keySix, valueSix) ? null : keySix;
}
 
源代码9 项目: rapidminer-studio   文件: AveragableTest.java
/**
 * Check if all fields are the same/similar after cloning; goes through all super class fields, too
 * relies {@link #specialEquals} map or Objects{@link #equals(Object)}
 */
private void testEqualityOfClone(Class<? extends Averagable> aClass, Averagable original, Averagable clone) {
	Class c = aClass;
	while (Averagable.class.isAssignableFrom(c)) {
		for (Field field : c.getDeclaredFields()) {
			field.setAccessible(true);
			try {
				Object originalField = field.get(original);
				Object clonedField = field.get(clone);
				if (!NULL_CHECK_EQUALS.test(originalField, clonedField)) {
					fail("Cloning field " + field + " failed: unexpected (non) null value "
							+ originalField + "/" + clonedField);
				}
				if (originalField == null) {
					continue;
				}
				Class<?> ofc = originalField.getClass();
				BiPredicate<Object, Object> equals = specialEquals.getOrDefault(ofc, Objects::equals);
				assertTrue("Cloning field " + field + " failed", equals.test(originalField, clonedField));
			} catch (IllegalAccessException e) {
				// ignore
			}
		}
		c = c.getSuperclass();
	}
}
 
源代码10 项目: arcusplatform   文件: KafkaStream.java
public KafkaStream<K, V> whileMatches(BiPredicate<? super K, ? super V> predicate) {
   BiPredicate<? super K, ? super V> keepGoing;
   if(this.keepGoing.isPresent()) {
      final BiPredicate<? super K, ? super V> delegate = this.keepGoing.get();
      keepGoing = (k, v) -> delegate.test(k, v) && predicate.test(k, v);
   }
   else {
      keepGoing = predicate;
   }

   return new KafkaStream<K, V>(
         config,
         keyDeserializer,
         valueDeserializer,
         Optional.of(keepGoing),
         filter
   );
}
 
源代码11 项目: ph-commons   文件: EqualsHelperTest.java
@Test
public void testEqualsCustom ()
{
  final MutableBoolean aPredCalled = new MutableBoolean (false);
  final BiPredicate <String, String> aPredicate = (x, y) -> {
    aPredCalled.set (true);
    return true;
  };

  assertTrue (EqualsHelper.equalsCustom (null, null, aPredicate));
  assertFalse (aPredCalled.booleanValue ());

  assertFalse (EqualsHelper.equalsCustom ("a", null, aPredicate));
  assertFalse (aPredCalled.booleanValue ());

  assertFalse (EqualsHelper.equalsCustom (null, "a", aPredicate));
  assertFalse (aPredCalled.booleanValue ());

  // Predicate is only called here
  assertTrue (EqualsHelper.equalsCustom ("b", "a", aPredicate));
  assertTrue (aPredCalled.booleanValue ());
}
 
源代码12 项目: mewbase   文件: QueryTest.java
@Test(expected = NoSuchElementException.class)
public void testNoSuchBinder() throws Exception {

    final BinderStore TEST_BINDER_STORE = BinderStore.instance(createConfig());

    QueryManager mgr = QueryManager.instance(TEST_BINDER_STORE);

    final String NON_EXISTENT_BINDER = "Junk";
    BiPredicate<BsonObject,KeyVal<String,BsonObject>> identity = (ctx, kv) -> true;

    mgr.queryBuilder().
            named(TEST_QUERY_NAME).
            from(NON_EXISTENT_BINDER).
            filteredBy(identity).
            create();
}
 
源代码13 项目: bullet-core   文件: ValidatorTest.java
@Test
public void testIsImpliedBy() {
    BiPredicate<Object, Object> isEnabledAndCheck = Validator.isImpliedBy(Validator::isTrue, Validator::isList);
    Assert.assertTrue(isEnabledAndCheck.test(true, emptyList()));
    Assert.assertTrue(isEnabledAndCheck.test(false, null));
    Assert.assertTrue(isEnabledAndCheck.test(false, null));
    Assert.assertFalse(isEnabledAndCheck.test(true, 8));
}
 
源代码14 项目: jane   文件: SMap.java
public boolean foreachFilter(Predicate<V> filter, BiPredicate<K, S> consumer)
{
	for (Entry<K, V> entry : _map.entrySet())
	{
		K k = entry.getKey();
		V v = entry.getValue();
		if (filter.test(v) && !consumer.test(k, safe(k, v)))
			return false;
	}
	return true;
}
 
源代码15 项目: throwing-function   文件: ThrowingBiPredicate.java
static <T, U> BiPredicate<T, U> unchecked(ThrowingBiPredicate<? super T, ? super U, ?> predicate) {
    requireNonNull(predicate);
    return (arg1, arg2) -> {
        try {
            return predicate.test(arg1, arg2);
        } catch (final Exception e) {
            throw new CheckedException(e);
        }
    };
}
 
源代码16 项目: Java-9-Cookbook   文件: Chapter04Functional.java
public void speedAfterStart(double timeSec, int trafficUnitsNumber, SpeedModel speedModel,
    BiPredicate<TrafficUnit, Double> limitSpeed, BiConsumer<TrafficUnit, Double> printResult) {
    List<TrafficUnit> trafficUnits = FactoryTraffic.generateTraffic(trafficUnitsNumber,
            month, dayOfWeek, hour, country, city, trafficLight);
    for(TrafficUnit tu: trafficUnits){
        Vehicle vehicle = FactoryVehicle.build(tu);
        vehicle.setSpeedModel(speedModel);
        double speed = vehicle.getSpeedMph(timeSec);
        speed = Math.round(speed * tu.getTraction());
        if(limitSpeed.test(tu, speed)){
            printResult.accept(tu, speed);
        }
    }
}
 
源代码17 项目: crate   文件: ShardsLimitAllocationDecider.java
private Decision doDecide(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation,
                          BiPredicate<Integer, Integer> decider) {
    IndexMetaData indexMd = allocation.metaData().getIndexSafe(shardRouting.index());
    final int indexShardLimit = INDEX_TOTAL_SHARDS_PER_NODE_SETTING.get(indexMd.getSettings(), settings);
    // Capture the limit here in case it changes during this method's
    // execution
    final int clusterShardLimit = this.clusterShardLimit;

    if (indexShardLimit <= 0 && clusterShardLimit <= 0) {
        return allocation.decision(Decision.YES, NAME, "total shard limits are disabled: [index: %d, cluster: %d] <= 0",
                indexShardLimit, clusterShardLimit);
    }

    int indexShardCount = 0;
    int nodeShardCount = 0;
    for (ShardRouting nodeShard : node) {
        // don't count relocating shards...
        if (nodeShard.relocating()) {
            continue;
        }
        nodeShardCount++;
        if (nodeShard.index().equals(shardRouting.index())) {
            indexShardCount++;
        }
    }

    if (clusterShardLimit > 0 && decider.test(nodeShardCount, clusterShardLimit)) {
        return allocation.decision(Decision.NO, NAME,
            "too many shards [%d] allocated to this node, cluster setting [%s=%d]",
            nodeShardCount, CLUSTER_TOTAL_SHARDS_PER_NODE_SETTING.getKey(), clusterShardLimit);
    }
    if (indexShardLimit > 0 && decider.test(indexShardCount, indexShardLimit)) {
        return allocation.decision(Decision.NO, NAME,
            "too many shards [%d] allocated to this node for index [%s], index setting [%s=%d]",
            indexShardCount, shardRouting.getIndexName(), INDEX_TOTAL_SHARDS_PER_NODE_SETTING.getKey(), indexShardLimit);
    }
    return allocation.decision(Decision.YES, NAME,
        "the shard count [%d] for this node is under the index limit [%d] and cluster level node limit [%d]",
        nodeShardCount, indexShardLimit, clusterShardLimit);
}
 
private Stream<UploadDataSupplier> getSharedFilesData(
    BiPredicate<Digest, String> requiredDataPredicate) throws IOException {
  ImmutableList<RequiredFile> requiredFiles = sharedRequiredFiles.get();
  return requiredFiles.stream()
      .map(requiredFile -> requiredFile.dataSupplier)
      .filter(
          dataSupplier ->
              requiredDataPredicate.test(dataSupplier.getDigest(), dataSupplier.describe()));
}
 
源代码19 项目: tablesaw   文件: BooleanColumn.java
public Selection eval(BiPredicate<Boolean, Boolean> predicate, Boolean valueToCompare) {
  Selection selection = new BitmapBackedSelection();
  for (int idx = 0; idx < data.size(); idx++) {
    if (predicate.test(get(idx), valueToCompare)) {
      selection.add(idx);
    }
  }
  return selection;
}
 
源代码20 项目: CQL   文件: Row.java
public boolean rowEquals(BiPredicate<X, X> f, Row<En2, X> e) {
	if (!this.en2.equals(e.en2)) {
		return false;
	}
	if (tail == null) {
		return e.tail == null;
	} else if (v.equals(e.v)) {
		return f.test(x, e.x) && tail.rowEquals(f, e.tail);
	}
	return Util.anomaly();
}
 
源代码21 项目: titus-control-plane   文件: ReactorExt.java
/**
 * An operator that converts collection of value into an event stream. Subsequent collection versions
 * are compared against each other and add/remove events are emitted accordingly.
 */
public static <K, T, E> Function<Flux<List<T>>, Publisher<E>> eventEmitter(
        Function<T, K> keyFun,
        BiPredicate<T, T> valueComparator,
        Function<T, E> valueAddedEventMapper,
        Function<T, E> valueRemovedEventMapper,
        E snapshotEndEvent) {
    return new EventEmitterTransformer<>(keyFun, valueComparator, valueAddedEventMapper, valueRemovedEventMapper, snapshotEndEvent);
}
 
源代码22 项目: 99-problems   文件: P46.java
public static String table(BiPredicate<Boolean, Boolean> f) {
    List<String> resultBuilder = new ArrayList<>();
    resultBuilder.add("A          B          result");
    for (boolean a : Arrays.asList(true, false)) {
        for (boolean b : Arrays.asList(true, false)) {
            resultBuilder.add(String.format("%-10s %-10s %s", a, b, f.test(a, b)));
        }
    }
    return resultBuilder.stream().collect(Collectors.joining("\n"));
}
 
源代码23 项目: armeria   文件: ContentPreviewerFactoryBuilder.java
/**
 * Sets the specified {@link BiPredicate} to produce the text preview when the predicate
 * returns {@code true}.
 */
public ContentPreviewerFactoryBuilder text(
        BiPredicate<? super RequestContext, ? super HttpHeaders> predicate) {
    requireNonNull(predicate, "predicate");
    previewSpecsBuilder.add(new PreviewSpec(predicate, PreviewMode.TEXT, null));
    return this;
}
 
源代码24 项目: hottub   文件: SerializedLambdaTest.java
public void testUnboundMR() throws IOException, ClassNotFoundException {
    class Moo {
        public boolean startsWithB(String s) {
            return s.startsWith("b");
        }
    }
    @SuppressWarnings("unchecked")
    BiPredicate<Moo, String> mh1 = (BiPredicate<Moo, String> & Serializable) Moo::startsWithB;
    Consumer<BiPredicate<Moo, String>> b = p -> {
        assertTrue(p instanceof Serializable);
        assertTrue(p.test(new Moo(), "barf"));
        assertFalse(p.test(new Moo(), "arf"));
    };
    assertSerial(mh1, b);
}
 
源代码25 项目: Wurst7   文件: NukerLegitHack.java
private Mode(String name, Function<NukerHack, String> renderName,
	BiPredicate<NukerHack, BlockPos> validator)
{
	this.name = name;
	this.renderName = renderName;
	this.validator = validator;
}
 
EventEmitterTransformer(
        Function<T, K> keyFun,
        BiPredicate<T, T> valueComparator,
        Function<T, E> valueAddedEventMapper,
        Function<T, E> valueRemovedEventMapper,
        E snapshotEndEvent) {
    this.keyFun = keyFun;
    this.valueComparator = valueComparator;
    this.valueAddedEventMapper = valueAddedEventMapper;
    this.valueRemovedEventMapper = valueRemovedEventMapper;
    this.snapshotEndEvent = snapshotEndEvent;
}
 
源代码27 项目: reactor-core   文件: MonoSequenceEqual.java
EqualCoordinator(CoreSubscriber<? super Boolean> actual, int prefetch,
		Publisher<? extends T> first, Publisher<? extends T> second,
		BiPredicate<? super T, ? super T> comparer) {
	this.actual = actual;
	this.first = first;
	this.second = second;
	this.comparer = comparer;
	firstSubscriber = new EqualSubscriber<>(this, prefetch);
	secondSubscriber = new EqualSubscriber<>(this, prefetch);
}
 
源代码28 项目: openjdk-jdk9   文件: Types.java
/**
 * Collect types into a new closure (using a @code{ClosureHolder})
 */
public Collector<Type, ClosureHolder, List<Type>> closureCollector(boolean minClosure, BiPredicate<Type, Type> shouldSkip) {
    return Collector.of(() -> new ClosureHolder(minClosure, shouldSkip),
            ClosureHolder::add,
            ClosureHolder::merge,
            ClosureHolder::closure);
}
 
public JSList(List srcmodel, Function<T, String> mapper,
        Function<String, T> onAdd, BiPredicate<String, String> predicate) {
    this.onAdd = onAdd;
    this.mapper = mapper;
    fltrmodel = new FilterModel(srcmodel, mapper, predicate);
    setLayout(new java.awt.BorderLayout());
    topBar = new TopBar(fltrmodel::doFilter);
    add(topBar, java.awt.BorderLayout.NORTH);
    listPanel = new ListPanel(fltrmodel, mapper);
    add(listPanel, java.awt.BorderLayout.CENTER);
    setSize(300, 380);
}
 
源代码30 项目: jane   文件: SMap.java
public boolean foreachFilter(BiPredicate<K, V> filter, Predicate<S> consumer)
{
	for (Entry<K, V> entry : _map.entrySet())
	{
		K k = entry.getKey();
		V v = entry.getValue();
		if (filter.test(k, v) && !consumer.test(safe(k, v)))
			return false;
	}
	return true;
}
 
 类所在包
 类方法
 同包方法