java.util.function.BiFunction Java Examples

The following examples show how to use java.util.function.BiFunction. 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: Hashtable.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public synchronized void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
    Objects.requireNonNull(function);     // explicit check required in case
                                          // table is empty.
    final int expectedModCount = modCount;

    Entry<K, V>[] tab = (Entry<K, V>[])table;
    for (Entry<K, V> entry : tab) {
        while (entry != null) {
            entry.value = Objects.requireNonNull(
                function.apply(entry.key, entry.value));
            entry = entry.next;

            if (expectedModCount != modCount) {
                throw new ConcurrentModificationException();
            }
        }
    }
}
 
Example #2
Source File: ProductReferenceResolver.java    From commercetools-sync-java with Apache License 2.0 6 votes vote down vote up
/**
 * Common function to resolve references from key.
 *
 * @param draftBuilder                 {@link ProductDraftBuilder} to update
 * @param resourceIdentifier           resourceIdentifier instance from which key is read
 * @param keyToIdMapper                function which calls respective service to fetch the reference by key
 * @param idToResourceIdentifierMapper function which creates {@link ResourceIdentifier} instance from fetched id
 * @param resourceIdentifierSetter     function which will set the resolved reference to the {@code productDraft}
 * @param <T>                          type of reference (e.g. {@link State}, {@link TaxCategory}
 * @return {@link CompletionStage} containing {@link ProductDraftBuilder} with resolved &lt;T&gt; reference.
 */
@Nonnull
private <T, S extends ResourceIdentifier<T>> CompletionStage<ProductDraftBuilder> resolveResourceIdentifier(
    @Nonnull final ProductDraftBuilder draftBuilder,
    @Nullable final S resourceIdentifier,
    @Nonnull final Function<String, CompletionStage<Optional<String>>> keyToIdMapper,
    @Nonnull final Function<String, S> idToResourceIdentifierMapper,
    @Nonnull final BiFunction<ProductDraftBuilder, S, ProductDraftBuilder> resourceIdentifierSetter)
    throws ReferenceResolutionException {

    if (resourceIdentifier == null) {
        return completedFuture(draftBuilder);
    }

    final String resourceKey = getKeyFromResourceIdentifier(resourceIdentifier);

    return keyToIdMapper
        .apply(resourceKey)
        .thenApply(optId -> optId
            .map(idToResourceIdentifierMapper)
            .map(resourceIdentifierToSet -> resourceIdentifierSetter.apply(draftBuilder, resourceIdentifierToSet))
            .orElse(draftBuilder));
}
 
Example #3
Source File: CheckedMapReplaceAll.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    Map<Integer,Double> unwrapped = new HashMap<>();
    unwrapped.put(1, 1.0);
    unwrapped.put(2, 2.0);
    unwrapped.put(3, 3.0);

    Map<Integer,Double> wrapped = Collections.checkedMap(unwrapped, Integer.class, Double.class);

    BiFunction evil = (k, v) -> (((int)k) % 2 != 0) ? v : "evil";

    try {
        wrapped.replaceAll(evil);
        System.out.printf("Bwahaha! I have defeated you! %s\n", wrapped);
        throw new RuntimeException("String added to checked Map<Integer,Double>");
    } catch (ClassCastException thwarted) {
        thwarted.printStackTrace(System.out);
        System.out.println("Curses! Foiled again!");
    }
}
 
Example #4
Source File: NpmPackageRootMetadataUtilsTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private void createFullPackageMetadataImpl(final BiFunction<String, String, String> function, String packageJsonFilename) throws URISyntaxException, IOException {
  try {
    assertThat(BaseUrlHolder.isSet(), is(false));
    BaseUrlHolder.set("http://localhost:8080/");

    File packageJsonFile = new File(NpmPackageRootMetadataUtilsTest.class.getResource(packageJsonFilename).toURI());
    File archive = tempFolderRule.newFile();
    Map<String, Object> packageJson = new NpmPackageParser()
        .parsePackageJson(() -> ArchiveUtils.pack(archive, packageJsonFile, "package/package.json"));

    NestedAttributesMap packageMetadata = NpmPackageRootMetadataUtils
        .createFullPackageMetadata(new NestedAttributesMap("metadata", packageJson),
            "npm-hosted",
            "abcd",
            repository,
            function);

    assertPackageMetadata(packageMetadata);
  }
  finally {
    BaseUrlHolder.unset();
  }
}
 
Example #5
Source File: ConfigDifference.java    From buck with Apache License 2.0 6 votes vote down vote up
/** Format a single config change */
public static String formatConfigChange(Entry<String, ConfigChange> change, boolean truncate) {
  String prevVal = change.getValue().getPrevValue();
  String newVal = change.getValue().getNewValue();
  BiFunction<String, Integer, String> abbrev =
      (value, width) -> truncate ? MoreStrings.abbreviate(value, width) : value;
  if (prevVal == null) {
    return String.format("New value %s='%s'", change.getKey(), abbrev.apply(newVal, 80));
  }
  if (newVal == null) {
    return String.format("Removed value %s='%s'", change.getKey(), abbrev.apply(prevVal, 80));
  }

  return String.format(
      "Changed value %s='%s' (was '%s')",
      change.getKey(), abbrev.apply(newVal, 40), abbrev.apply(prevVal, 40));
}
 
Example #6
Source File: MonitoringServiceTest.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
public void testGetStatusWithSelfMonitoringRestartNeeded() {
    BiFunction<String, Optional<String>, Optional<InputStream>> execCtl =
            (String cmd, Optional<String> pillar) -> {
                return Optional.of(this.getClass()
                        .getResourceAsStream("/com/suse/manager/webui/services/impl/test/monitoring/status_self_monitoring_restart.json"));
            };

    MonitoringService.setExecCtlFunction(execCtl);
    MonitoringService.setTomcatJmxStatusSupplier(() -> true);
    MonitoringService.setTaskomaticJmxStatusSupplier(() -> true);
    MonitoringService.setSelfMonitoringStatusSupplier(() -> false);

    Optional<MonitoringService.MonitoringStatus> res = MonitoringService.getStatus();
    assertTrue(res.isPresent());
    assertTrue(res.get().getExporters().get("node"));
    assertTrue(res.get().getExporters().get("postgres"));
    assertTrue(res.get().getExporters().get("tomcat"));
    assertTrue(res.get().getExporters().get("taskomatic"));
    assertTrue(res.get().getExporters().get("self_monitoring"));
    assertEquals(null, res.get().getMessages().get("tomcat"));
    assertEquals("enable", res.get().getMessages().get("taskomatic"));
    assertEquals("restart", res.get().getMessages().get("self_monitoring"));
}
 
Example #7
Source File: UuidCoercer.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public BiFunction<JsonInput, PropertySetting, UUID> apply(Type type) {
  return (jsonInput, propertySetting) -> {
    String toCoerce;

    switch (jsonInput.peek()) {
      case NAME:
        toCoerce = jsonInput.nextName();
        break;

      case STRING:
        toCoerce = jsonInput.nextString();
        break;

      default:
        throw new JsonException("Unable to coerce type to URL: " + jsonInput.peek());
    }

    return UUID.fromString(toCoerce);
  };
}
 
Example #8
Source File: FluxBlackboxProcessorVerification.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
	Flux<Integer> transformFlux(Flux<Integer> f) {
		Flux<String> otherStream = Flux.just("test", "test2", "test3");
//		System.out.println("Providing new downstream");

		Scheduler asyncGroup = Schedulers.newParallel("flux-p-tck", 2);

		BiFunction<Integer, String, Integer> combinator = (t1, t2) -> t1;

		return f.publishOn(sharedGroup)
		        .parallel(2)
		        .groups()
		        .flatMap(stream -> stream.publishOn(asyncGroup)
				                          .doOnNext(this::monitorThreadUse)
				                          .scan((prev, next) -> next)
				                          .map(integer -> -integer)
				                          .filter(integer -> integer <= 0)
				                          .map(integer -> -integer)
				                          .bufferTimeout(batch, Duration.ofMillis(50))
				                          .flatMap(Flux::fromIterable)
				                          .flatMap(i -> Flux.zip(Flux.just(i), otherStream, combinator))
				 )
		        .publishOn(sharedGroup)
		        .doAfterTerminate(asyncGroup::dispose)
		        .doOnError(Throwable::printStackTrace);
	}
 
Example #9
Source File: TableMetadataStore.java    From pravega with Apache License 2.0 6 votes vote down vote up
private <T> CompletableFuture<T> applyToSegment(String segmentName, BiFunction<TableEntry, Duration, CompletableFuture<T>> ifExists,
                                                Supplier<CompletableFuture<T>> ifNotExists, Duration timeout) {
    ensureInitialized();
    ArrayView key = getTableKey(segmentName);
    TimeoutTimer timer = new TimeoutTimer(timeout);
    return this.tableStore
            .get(this.metadataSegmentName, Collections.singletonList(key), timer.getRemaining())
            .thenComposeAsync(existingData -> {
                assert existingData.size() == 1 : "Expecting only one result";
                if (existingData.get(0) == null) {
                    // We don't know anything about this Segment.
                    return ifNotExists.get();
                }

                // We have an entry.
                return ifExists.apply(existingData.get(0), timer.getRemaining());
            }, this.executor);
}
 
Example #10
Source File: CustomReferenceResolver.java    From commercetools-sync-java with Apache License 2.0 6 votes vote down vote up
/**
 * Given a draft of {@code D} (e.g. {@link CategoryDraft}) this method attempts to resolve it's custom type
 * reference to return {@link CompletionStage} which contains a new instance of the draft with the resolved
 * custom type reference. The key of the custom type is taken from the from the id field of the reference.
 *
 * <p>The method then tries to fetch the key of the custom type, optimistically from a
 * cache. If the key is is not found, the resultant draft would remain exactly the same as the passed
 * draft (without a custom type reference resolution).
 *
 * @param draftBuilder the draft builder to resolve it's references.
 * @param customGetter a function to return the CustomFieldsDraft instance of the draft builder.
 * @param customSetter a function to set the CustomFieldsDraft instance of the builder and return this builder.
 * @param errorMessage the error message to inject in the {@link ReferenceResolutionException} if it occurs.
 * @return a {@link CompletionStage} that contains as a result a new draft instance with resolved custom
 *         type references or, in case an error occurs during reference resolution,
 *         a {@link ReferenceResolutionException}.
 */
@Nonnull
protected CompletionStage<B> resolveCustomTypeReference(
    @Nonnull final B draftBuilder,
    @Nonnull final Function<B, CustomFieldsDraft> customGetter,
    @Nonnull final BiFunction<B, CustomFieldsDraft, B> customSetter,
    @Nonnull final String errorMessage) {

    final CustomFieldsDraft custom = customGetter.apply(draftBuilder);
    if (custom != null) {
        return getCustomTypeId(custom, errorMessage)
            .thenApply(resolvedTypeIdOptional ->
                resolvedTypeIdOptional.map(resolvedTypeId ->
                    customSetter.apply(draftBuilder, ofTypeIdAndJson(resolvedTypeId, custom.getFields())))
                                      .orElse(draftBuilder));
    }
    return CompletableFuture.completedFuture(draftBuilder);
}
 
Example #11
Source File: DefaultCallOptionsClientInterceptor.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private <T> CallOptions patchOption(CallOptions baseOptions, Function<CallOptions, T> getter, BiFunction<CallOptions, T, CallOptions> setter) {
    T baseValue = getter.apply(baseOptions);
    if (baseValue == null || overwrite) {
        T patchValue = getter.apply(defaultOptions);
        if (patchValue != null) {
            return setter.apply(baseOptions, patchValue);
        }
    }

    return baseOptions;
}
 
Example #12
Source File: CommandSubscriptionsManager.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Closes the command consumer and removes the subscription entry for the given topic.
 *
 * @param topic The topic string to unsubscribe.
 * @param onConsumerRemovedFunction The function to be invoked if not {@code null} during removal of a subscription.
 *                                  The first parameter is the tenant id, the second parameter the device id.
 *                                  To be returned is a future indicating the outcome of the function.
 * @param spanContext The span context (may be {@code null}).
 * @throws NullPointerException if topic is {@code null}.
 * @return A future indicating the outcome of the operation.
 **/
public Future<Void> removeSubscription(final String topic,
        final BiFunction<String, String, Future<Void>> onConsumerRemovedFunction, final SpanContext spanContext) {
    Objects.requireNonNull(topic);

    final TriTuple<CommandSubscription, ProtocolAdapterCommandConsumer, Object> removed = subscriptions.remove(topic);
    if (removed != null) {
        final CommandSubscription subscription = removed.one();
        final Future<Void> functionFuture = onConsumerRemovedFunction != null
                ? onConsumerRemovedFunction.apply(subscription.getTenant(), subscription.getDeviceId())
                : Future.succeededFuture();
        final ProtocolAdapterCommandConsumer commandConsumer = removed.two();
        return CompositeFuture
                .join(functionFuture, closeCommandConsumer(subscription, commandConsumer, spanContext)).mapEmpty();
    } else {
        LOG.debug("Cannot remove subscription; none registered for topic [{}]", topic);
        return Future.failedFuture(String.format("Cannot remove subscription; none registered for topic [%s]", topic));
    }
}
 
Example #13
Source File: E2EProjectAPIControllerSecurityTest.java    From ods-provisioning-app with Apache License 2.0 5 votes vote down vote up
public void assertRequest(
    BiFunction<String, String, HttpStatus> request,
    String username,
    String credential,
    HttpStatus expected) {

  HttpStatus responseStatus = request.apply(username, credential);
  assertEquals(
      String.format(
          "Authentication failed with unexpected return code for user '%s:%s' ",
          username, credential),
      expected,
      responseStatus);
}
 
Example #14
Source File: AsyncCacheTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@CheckNoWriter @CheckNoStats
@Test(dataProvider = "caches", expectedExceptions = NullPointerException.class)
@CacheSpec(removalListener = { Listener.DEFAULT, Listener.REJECTING })
public void getAllBifunction_nullBifunction(
    AsyncCache<Integer, Integer> cache, CacheContext context) {
  @SuppressWarnings("unused")
  BiFunction<Iterable<? extends Integer>, Executor, CompletableFuture<Map<Integer, Integer>>> f;
  cache.getAll(context.original().keySet(), (f = null));
}
 
Example #15
Source File: Provider.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked") // Function must actually operate over strings
private Object implComputeIfPresent(Object key, BiFunction<? super Object,
        ? super Object, ? extends Object> remappingFunction) {
    if (key instanceof String) {
        if (isProviderInfo(key)) {
            return null;
        }
        legacyChanged = true;
    }
    return super.computeIfPresent(key, remappingFunction);
}
 
Example #16
Source File: RaftSessionConnection.java    From atomix with Apache License 2.0 5 votes vote down vote up
/**
 * Resends a request due to a request failure, resetting the connection if necessary.
 */
@SuppressWarnings("unchecked")
protected <T extends RaftRequest> void retryRequest(Throwable cause, T request, BiFunction sender, int count, int selectionId, CompletableFuture future) {
  // If the connection has not changed, reset it and connect to the next server.
  if (this.selectionId == selectionId) {
    log.trace("Resetting connection. Reason: {}", cause.getMessage());
    this.currentNode = null;
  }

  // Attempt to send the request again.
  sendRequest(request, sender, count, future);
}
 
Example #17
Source File: ClientPolicyForm.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected BiFunction<WebElement, String, Boolean> deselect() {
    return (webElement, name) -> {
        List<WebElement> tds = webElement.findElements(tagName("td"));

        if (!UIUtils.getTextFromElement(tds.get(0)).isEmpty()) {
            if (UIUtils.getTextFromElement(tds.get(0)).equals(name)) {
                tds.get(1).findElement(By.tagName("button")).click();
                return true;
            }
        }

        return false;
    };
}
 
Example #18
Source File: ProcessDrawUtils.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Returns a {@link Rectangle2D} representing an {@link Operator}. First tries to look up the
 * data from the model, if that fails it determines a position automatically. Uses the given
 * {@link ProcessRendererModel} to determine layout properties. May use a supplied {@link BiFunction}
 * to check some dependencies
 *
 * @param op
 * 		the operator for which a rectangle should be created
 * @param model
 * 		the reference process model
 * @param checkDependencies
 * 		an optional dependency check
 * @return the rectangle representing the operator, never {@code null}
 * @since 8.2
 */
public static Rectangle2D createOperatorPosition(Operator op, ProcessRendererModel model, BiFunction<Operator, ProcessRendererModel, Boolean> checkDependencies) {
	Rectangle2D rect = model.getOperatorRect(op);
	if (rect != null) {
		return rect;
	}

	// if connected (e.g. because inserted by quick fix), place in the middle
	if (op.getInputPorts().getNumberOfPorts() > 0 && op.getOutputPorts().getNumberOfPorts() > 0
			&& op.getInputPorts().getPortByIndex(0).isConnected()
			&& op.getOutputPorts().getPortByIndex(0).isConnected()
			// see ProcessRendererController#isDependenciesOk
			&& (checkDependencies == null || checkDependencies.apply(op, model))) {
		Point2D sourcePos = ProcessDrawUtils.createPortLocation(op.getInputPorts().getPortByIndex(0).getSource(), model);
		Point2D destPos = ProcessDrawUtils.createPortLocation(op.getOutputPorts().getPortByIndex(0).getDestination(),
				model);
		if (sourcePos != null && destPos != null) {
			double x = Math.floor((sourcePos.getX() + destPos.getX()) / 2d - ProcessDrawer.OPERATOR_WIDTH / 2d);
			double y = Math.floor((sourcePos.getY() + destPos.getY()) / 2d - ProcessDrawer.PORT_OFFSET);
			return new Rectangle2D.Double(x, y, ProcessDrawer.OPERATOR_WIDTH, calcHeighForOperator(op));
		}
	}
	// otherwise, or, if positions were not known in previous approach, position according to index
	int index = 0;
	ExecutionUnit unit = op.getExecutionUnit();
	if (unit != null) {
		index = unit.getOperators().indexOf(op);
	}
	return autoPosition(op, index, model);
}
 
Example #19
Source File: RetryRuleBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
private RetryRule build(RetryDecision decision) {
    if (decision != RetryDecision.noRetry() &&
        exceptionFilter() == null && responseHeadersFilter() == null && responseTrailersFilter() == null) {
        throw new IllegalStateException("Should set at least one retry rule if a backoff was set.");
    }
    final BiFunction<? super ClientRequestContext, ? super Throwable, Boolean> ruleFilter =
            AbstractRuleBuilderUtil.buildFilter(requestHeadersFilter(), responseHeadersFilter(),
                                                responseTrailersFilter(), exceptionFilter(), false);
    return build(ruleFilter, decision, responseTrailersFilter() != null);
}
 
Example #20
Source File: RuntimeContext.java    From es6draft with MIT License 5 votes vote down vote up
RuntimeContext(Supplier<? extends RuntimeContext.Data> runtimeData, Function<Realm, ? extends RealmData> realmData,
        BiFunction<RuntimeContext, ScriptLoader, ? extends ModuleLoader> moduleLoader, Locale locale,
        TimeZone timeZone, Path baseDirectory, Console console, ScriptCache scriptCache, ExecutorService executor,
        BiConsumer<ExecutionContext, Throwable> errorReporter, ExecutorService workerExecutor,
        BiConsumer<ExecutionContext, Throwable> workerErrorReporter, Futex futex,
        Consumer<ExecutionContext> debugger, BiFunction<String, MethodType, MethodHandle> nativeCallResolver,
        BiConsumer<ScriptObject, ModuleRecord> importMeta, EnumSet<CompatibilityOption> options,
        EnumSet<Parser.Option> parserOptions, EnumSet<Compiler.Option> compilerOptions) {
    this.runtimeData = runtimeData;
    this.contextData = runtimeData.get();
    this.realmData = realmData;
    this.moduleLoader = moduleLoader;
    this.locale = locale;
    this.timeZone = timeZone;
    this.baseDirectory = baseDirectory;
    this.console = console;
    this.scriptCache = scriptCache;
    this.executor = executor != null ? executor : createThreadPoolExecutor();
    this.shutdownExecutorOnFinalization = executor == null;
    this.workerExecutor = workerExecutor != null ? workerExecutor : createWorkerThreadPoolExecutor();
    this.shutdownWorkerExecutorOnFinalization = workerExecutor == null;
    this.errorReporter = errorReporter;
    this.workerErrorReporter = workerErrorReporter;
    this.futex = futex;
    this.debugger = debugger;
    this.nativeCallResolver = nativeCallResolver;
    this.importMeta = importMeta;
    this.options = EnumSet.copyOf(options);
    this.parserOptions = EnumSet.copyOf(parserOptions);
    this.compilerOptions = EnumSet.copyOf(compilerOptions);
}
 
Example #21
Source File: ListT.java    From cyclops with Apache License 2.0 5 votes vote down vote up
public <T2, R1, R2, R> ListT<W,R> forEach3M(Function<? super T, ? extends ListT<W,R1>> value1,
                                            BiFunction<? super T, ? super R1, ? extends ListT<W,R2>> value2,
                                            Function3<? super T, ? super R1, ? super R2, ? extends R> yieldingFunction) {

    return this.flatMapT(in->value1.apply(in).flatMapT(in2-> value2.apply(in,in2)
            .map(in3->yieldingFunction.apply(in,in2,in3))));

}
 
Example #22
Source File: ThrottlingStrategy.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link ThrottlingStrategy} that determines whether a request should be accepted or not
 * using a given {@link BiFunction} instance.
 */
public static <T extends Request> ThrottlingStrategy<T> of(
        BiFunction<ServiceRequestContext, T, CompletionStage<Boolean>> function) {
    return new ThrottlingStrategy<T>(null) {
        @Override
        public CompletionStage<Boolean> accept(ServiceRequestContext ctx, T request) {
            return function.apply(ctx, request);
        }
    };
}
 
Example #23
Source File: SimpleAckingTaskManagerGateway.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Acknowledge> freeSlot(AllocationID allocationId, Throwable cause, Time timeout) {
	final BiFunction<AllocationID, Throwable, CompletableFuture<Acknowledge>> currentFreeSlotFunction = freeSlotFunction;

	if (currentFreeSlotFunction != null) {
		return currentFreeSlotFunction.apply(allocationId, cause);
	} else {
		return CompletableFuture.completedFuture(Acknowledge.get());
	}
}
 
Example #24
Source File: _Dept.java    From doma with Apache License 2.0 5 votes vote down vote up
@Override
public String getTableName(BiFunction<NamingType, String, String> namingFunction) {
  if (__tableName.isEmpty()) {
    return namingFunction.apply(getNamingType(), getName());
  }
  return __tableName;
}
 
Example #25
Source File: SeleniumGridWithCapabilitiesDriverFactoryFactoryBase.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
@Override
public DriverFactory getDriverFactory() {
    String gridUrl = getProperty(SELENIUM_GRID_URL);
    Map<String, Object> capabilities = getCapabilities();
    DesiredCapabilities desiredCapabilities = new DesiredCapabilities(capabilities);
    BiFunction<URL, Capabilities, RemoteWebDriver> constr = getRemoteWebDriverConstructor();
    return new RemoteDriverFactory(constr, gridUrl, desiredCapabilities);
}
 
Example #26
Source File: TreeMap.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
    Objects.requireNonNull(function);
    int expectedModCount = modCount;

    for (Entry<K, V> e = getFirstEntry(); e != null; e = successor(e)) {
        e.value = function.apply(e.key, e.value);

        if (expectedModCount != modCount) {
            throw new ConcurrentModificationException();
        }
    }
}
 
Example #27
Source File: StatisticsService.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public void manageTagToRows(List<AggregatedReportRow> rows, BiFunction<TestCaseRun, List<Tag>, Boolean> targetAction,
                            List<Tag> tags) {
    List<Object> testCaseRuns = new ArrayList<>();
    manageTagToRows(rows, targetAction, tags, testCaseRuns);
    if (!testCaseRuns.isEmpty()) {
        storage.update(testCaseRuns);
    }
}
 
Example #28
Source File: CompletableFuture.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private <U,V> CompletableFuture<V> biApplyStage(
    Executor e, CompletionStage<U> o,
    BiFunction<? super T,? super U,? extends V> f) {
    CompletableFuture<U> b;
    if (f == null || (b = o.toCompletableFuture()) == null)
        throw new NullPointerException();
    CompletableFuture<V> d = new CompletableFuture<V>();
    if (e != null || !d.biApply(this, b, f, null)) {
        BiApply<T,U,V> c = new BiApply<T,U,V>(e, d, this, b, f);
        bipush(b, c);
        c.tryFire(SYNC);
    }
    return d;
}
 
Example #29
Source File: KafkaSpanStore.java    From zipkin-storage-kafka with Apache License 2.0 5 votes vote down vote up
GetRemoteServiceNamesCall(KafkaStreams traceStoreStream, String serviceName,
    BiFunction<String, Integer, String> httpBaseUrl) {
  super(traceStoreStream, REMOTE_SERVICE_NAMES_STORE_NAME, httpBaseUrl,
      "/serviceNames/" + serviceName + "/remoteServiceNames", serviceName);
  this.traceStoreStream = traceStoreStream;
  this.serviceName = serviceName;
  this.httpBaseUrl = httpBaseUrl;
}
 
Example #30
Source File: Function2.java    From cyclops with Apache License 2.0 4 votes vote down vote up
public static <T1, T2, R> Function2<T1,T2, R> of(final BiFunction<T1,T2, R> triFunc){
  return (a,b)->triFunc.apply(a,b);
}