下面列出了怎么用java.util.function.BiPredicate的API类实例代码及写法,或者点击链接到github查看源代码。
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();
}
/**
* 移除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;
}
/**
* 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);
}
}
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 );
}
@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);
}
@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);
}
}
@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;
}
/**
* 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();
}
}
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
);
}
@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 ());
}
@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();
}
@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));
}
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;
}
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);
}
};
}
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);
}
}
}
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()));
}
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;
}
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();
}
/**
* 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);
}
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"));
}
/**
* 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;
}
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);
}
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;
}
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);
}
/**
* 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);
}