Java Code Examples for java.util.function.BiFunction#apply()

The following examples show how to use java.util.function.BiFunction#apply() . 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: IdentityHashMap.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
    Objects.requireNonNull(function);
    int expectedModCount = modCount;

    Object[] t = table;
    for (int index = 0; index < t.length; index += 2) {
        Object k = t[index];
        if (k != null) {
            t[index + 1] = function.apply((K) unmaskNull(k), (V) t[index + 1]);
        }

        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }
}
 
Example 2
Source File: Sodium.java    From cava with Apache License 2.0 6 votes vote down vote up
static <T> T scalarMult(Pointer n, long nlen, Pointer p, long plen, BiFunction<Pointer, Long, T> ctr) {
  if (nlen != Sodium.crypto_scalarmult_scalarbytes()) {
    throw new IllegalArgumentException(
        "secret key length is " + nlen + " but required " + Sodium.crypto_scalarmult_scalarbytes());
  }
  if (plen != Sodium.crypto_scalarmult_bytes()) {
    throw new IllegalArgumentException(
        "public key length is " + plen + " but required " + Sodium.crypto_scalarmult_bytes());
  }
  long qbytes = Sodium.crypto_scalarmult_bytes();
  Pointer dst = malloc(qbytes);
  try {
    int rc = Sodium.crypto_scalarmult(dst, n, p);
    if (rc != 0) {
      throw new SodiumException("crypto_scalarmult_base: failed with result " + rc);
    }
    return ctr.apply(dst, qbytes);
  } catch (Throwable e) {
    sodium_free(dst);
    throw e;
  }
}
 
Example 3
Source File: EventStream.java    From ReactFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
default <A> AwaitingEventStream<T> thenAccumulateFor(
        Duration duration,
        Supplier<? extends A> unit,
        BiFunction<? super A, ? super T, ? extends A> reduction,
        Function<? super A, List<T>> deconstruction,
        ScheduledExecutorService scheduler,
        Executor eventThreadExecutor) {
    Function<? super T, ? extends A> initialTransformation =
            t -> reduction.apply(unit.get(), t);
    return thenAccumulateFor(
            duration,
            initialTransformation,
            reduction,
            deconstruction,
            scheduler,
            eventThreadExecutor);
}
 
Example 4
Source File: ConcurrentSkipListMap.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * If the value for the specified key is present, attempts to
 * compute a new mapping given the key and its current mapped
 * value. The function is <em>NOT</em> guaranteed to be applied
 * once atomically.
 *
 * @param key key with which a value may be associated
 * @param remappingFunction the function to compute a value
 * @return the new value associated with the specified key, or null if none
 * @throws NullPointerException if the specified key is null
 *         or the remappingFunction is null
 * @since 1.8
 */
public V computeIfPresent(K key,
                          BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
    if (key == null || remappingFunction == null)
        throw new NullPointerException();
    Node<K,V> n; Object v;
    while ((n = findNode(key)) != null) {
        if ((v = n.value) != null) {
            @SuppressWarnings("unchecked") V vv = (V) v;
            V r = remappingFunction.apply(key, vv);
            if (r != null) {
                if (n.casValue(vv, r))
                    return r;
            }
            else if (doRemove(key, vv) != null)
                break;
        }
    }
    return null;
}
 
Example 5
Source File: PluginContext.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
private String convertWord(final String str, final BiFunction<NameConverter, String, String> converterFunction) {
	String name;
	// This is similar to the logic used in CPropertyInfo
	if (outline.getModel() != null) {
		name = converterFunction.apply(outline.getModel().getNameConverter(), str);
	} else {
		name = converterFunction.apply(NameConverter.standard, str);
	}
	// Prefix name with _ if it is a reserved java identifier
	if (!JJavaName.isJavaIdentifier(name)) {
		return '_' + name;
	} else {
		return name;
	}
}
 
Example 6
Source File: MessagingSandboxTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** */
private void execute(Ignite node, BiFunction<IgniteMessaging, String, UUID> func, boolean isForbiddenCase) {
    final String topic = "test_topic";

    IgniteMessaging messaging = node.message(node.cluster().forNodeId(grid(SRV).localNode().id()));

    UUID listenerId = func.apply(messaging, topic);

    try {
        GridTestUtils.RunnableX r = () -> {
            error = null;

            latch = new CountDownLatch(1);

            grid(SRV_SENDER).message().send(topic, "Hello!");

            latch.await(10, TimeUnit.SECONDS);

            if (error != null)
                throw error;
        };

        if (isForbiddenCase)
            runForbiddenOperation(r, AccessControlException.class);
        else
            runOperation(r);
    }
    finally {
        messaging.stopRemoteListen(listenerId);
    }
}
 
Example 7
Source File: Hashtable.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public synchronized V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
    Objects.requireNonNull(remappingFunction);

    Entry<?,?> tab[] = table;
    int hash = key.hashCode();
    int index = (hash & 0x7FFFFFFF) % tab.length;
    @SuppressWarnings("unchecked")
    Entry<K,V> e = (Entry<K,V>)tab[index];
    for (Entry<K,V> prev = null; e != null; prev = e, e = e.next) {
        if (e.hash == hash && e.key.equals(key)) {
            V newValue = remappingFunction.apply(key, e.value);
            if (newValue == null) {
                modCount++;
                if (prev != null) {
                    prev.next = e.next;
                } else {
                    tab[index] = e.next;
                }
                count--;
            } else {
                e.value = newValue;
            }
            return newValue;
        }
    }
    return null;
}
 
Example 8
Source File: CompleteExceptionallyPromise.java    From datakernel with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@NotNull
@Override
public <U> Promise<U> thenEx(@NotNull BiFunction<? super T, Throwable, ? extends Promise<? extends U>> fn) {
	try {
		return (Promise<U>) fn.apply(null, exception);
	} catch (UncheckedException u) {
		return Promise.ofException(u.getCause());
	}
}
 
Example 9
Source File: SparkCombineFn.java    From beam with Apache License 2.0 5 votes vote down vote up
private WindowFn<Object, BoundedWindow>.MergeContext asMergeContext(
    WindowFn<Object, BoundedWindow> windowFn,
    BiFunction<AccumT, AccumT, AccumT> mergeFn,
    BiConsumer<Collection<BoundedWindow>, KV<BoundedWindow, AccumT>> afterMerge,
    Map<BoundedWindow, WindowedValue<AccumT>> map) {

  return windowFn.new MergeContext() {

    @Override
    public Collection<BoundedWindow> windows() {
      return map.keySet();
    }

    @Override
    public void merge(Collection<BoundedWindow> toBeMerged, BoundedWindow mergeResult) {
      AccumT accumulator = null;
      for (BoundedWindow w : toBeMerged) {
        WindowedValue<AccumT> windowAccumulator = Objects.requireNonNull(map.get(w));
        if (accumulator == null) {
          accumulator = windowAccumulator.getValue();
        } else {
          accumulator = mergeFn.apply(accumulator, windowAccumulator.getValue());
        }
      }
      afterMerge.accept(toBeMerged, KV.of(mergeResult, accumulator));
    }
  };
}
 
Example 10
Source File: BlockchainDataIntegrationTest.java    From exonum-java-binding with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("accessConstructors")
void getDispatcherSchema(BiFunction<Database, Cleaner, AbstractAccess> accessCtor) {
  AbstractAccess access = accessCtor.apply(db, cleaner);
  BlockchainData blockchainData = BlockchainData.fromRawAccess(access, "test-service");

  DispatcherSchema dispatcherSchema = blockchainData.getDispatcherSchema();
  // Check it works
  ProofMapIndexProxy<String, InstanceState> instances = dispatcherSchema.serviceInstances();
  assertTrue(instances.isEmpty());

  // Check it is readonly
  assertThrows(UnsupportedOperationException.class,
      () -> instances.put("test-service-2", InstanceState.getDefaultInstance()));
}
 
Example 11
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 12
Source File: ClavaNodeParser.java    From clava with Apache License 2.0 5 votes vote down vote up
private ClavaNode buildChildlessNode(String nodeId, List<ClavaNode> children, String classname, boolean debug,
        DataStore nodeData,
        Class<? extends ClavaNode> clavaNodeClass) {
    // Get constructor based on DataStore
    BiFunction<DataStore, List<? extends ClavaNode>, ClavaNode> dataStoreBuilder = classesService
            .getClavaNodeBuilder(clavaNodeClass);

    if (dataStoreBuilder != null) {
        // Build node based on data and children
        // return dataStoreBuilder.apply(nodeData, children);
        return dataStoreBuilder.apply(nodeData, children);
    }

    if (!missingConstructors.contains(classname)) {

        // throw new RuntimeException(
        // "No builder for node '" + nodeId + "', missing constructor 'new " + classname + "("
        // + DataStore.class.getSimpleName()
        // + " data, Collection<? extends ClavaNode> children)'");

        missingConstructors.add(classname);
        if (debug) {
            SpecsLogs
                    .msgInfo("No builder for node '" + nodeId + "', missing constructor 'new " + classname + "("
                            + DataStore.class.getSimpleName()
                            + " data, Collection<? extends ClavaNode> children)'");
        }
    }

    // return DummyNode.newInstance(clavaNodeClass, nodeData, children, false);
    return DummyNode.newInstance(clavaNodeClass, nodeData, children, false);
}
 
Example 13
Source File: MapNodes.java    From bifurcan with MIT License 5 votes vote down vote up
public <U> Collision<K, U> mapVals(Object editor, BiFunction<K, V, U> f) {
  Collision c = new Collision(hash, entries.clone());
  for (int i = 0; i < entries.length; i += 2) {
    c.entries[i + 1] = f.apply((K) c.entries[i], (V) c.entries[i + 1]);
  }

  return c;
}
 
Example 14
Source File: Memo.java    From symbolicautomata with Apache License 2.0 4 votes vote down vote up
public Memo(BiFunction<Function<T,R>,T,R> f) {
	Function<T, R> app = (y) -> this.apply(y);
	fn = (x) -> f.apply(app, x);
}
 
Example 15
Source File: By.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends SearchContext> WebElement findElement(T driver, BiFunction<String, String, WebElement> finder) {
  return finder.apply("css selector", cssSelector);
}
 
Example 16
Source File: AbstractDataPointGeneratorImpl.java    From sample-data-generator with Apache License 2.0 4 votes vote down vote up
/**
 * @param measure a measure
 * @return a data point corresponding to the specified measure
 */
public DataPoint<T> newDataPoint(T measure) {

    TimeInterval effectiveTimeInterval = measure.getEffectiveTimeFrame().getTimeInterval();
    OffsetDateTime effectiveEndDateTime;

    if (effectiveTimeInterval != null) {
        if (effectiveTimeInterval.getEndDateTime() != null) {
            effectiveEndDateTime = effectiveTimeInterval.getEndDateTime();
        }
        else {
            // use the duration to calculate the end date time of the interval
            if (effectiveTimeInterval.getDuration() != null) {

                BiFunction<OffsetDateTime, Long, OffsetDateTime> plusFunction;

                switch (effectiveTimeInterval.getDuration().getTypedUnit()) {

                    case SECOND:
                        plusFunction = OffsetDateTime::plusSeconds;
                        break;
                    case MINUTE:
                        plusFunction = OffsetDateTime::plusMinutes;
                        break;
                    case HOUR:
                        plusFunction = OffsetDateTime::plusHours;
                        break;
                    case DAY:
                        plusFunction = OffsetDateTime::plusDays;
                        break;
                    case WEEK:
                        plusFunction = OffsetDateTime::plusWeeks;
                        break;
                    case MONTH:
                        plusFunction = OffsetDateTime::plusMonths;
                        break;
                    case YEAR:
                        plusFunction = OffsetDateTime::plusYears;
                        break;
                    default:
                        throw new IllegalStateException("A time interval duration type isn't supported.");
                }

                effectiveEndDateTime = plusFunction.apply(effectiveTimeInterval.getStartDateTime(),
                        effectiveTimeInterval.getDuration().getValue().longValue());
            }
            else {
                throw new IllegalStateException("An end date time can't be calculated without a duration.");
            }
        }
    }
    else { // if this is a point in time measure
        effectiveEndDateTime = measure.getEffectiveTimeFrame().getDateTime();
    }

    DataPointAcquisitionProvenance acquisitionProvenance =
            new DataPointAcquisitionProvenance.Builder(sourceName)
                    .setModality(SENSED)
                    .setSourceCreationDateTime(effectiveEndDateTime)
                    .build();

    DataPointHeader header =
            new DataPointHeader.Builder(randomUUID().toString(), measure.getSchemaId(),
                    effectiveEndDateTime.plusMinutes(1))
                    .setAcquisitionProvenance(acquisitionProvenance)
                    .setUserId(userId)
                    .build();

    return new DataPoint<>(header, measure);
}
 
Example 17
Source File: HashMap.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public V merge(K key, V value,
               BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
    if (value == null)
        throw new NullPointerException();
    if (remappingFunction == null)
        throw new NullPointerException();
    int hash = hash(key);
    Node<K,V>[] tab; Node<K,V> first; int n, i;
    int binCount = 0;
    TreeNode<K,V> t = null;
    Node<K,V> old = null;
    if (size > threshold || (tab = table) == null ||
        (n = tab.length) == 0)
        n = (tab = resize()).length;
    if ((first = tab[i = (n - 1) & hash]) != null) {
        if (first instanceof TreeNode)
            old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
        else {
            Node<K,V> e = first; K k;
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k)))) {
                    old = e;
                    break;
                }
                ++binCount;
            } while ((e = e.next) != null);
        }
    }
    if (old != null) {
        V v;
        if (old.value != null)
            v = remappingFunction.apply(old.value, value);
        else
            v = value;
        if (v != null) {
            old.value = v;
            afterNodeAccess(old);
        }
        else
            removeNode(hash, key, null, false, true);
        return v;
    }
    if (value != null) {
        if (t != null)
            t.putTreeVal(this, tab, hash, key, value);
        else {
            tab[i] = newNode(hash, key, value, first);
            if (binCount >= TREEIFY_THRESHOLD - 1)
                treeifyBin(tab, hash);
        }
        ++modCount;
        ++size;
        afterNodeInsertion(true);
    }
    return value;
}
 
Example 18
Source File: By.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends SearchContext> List<WebElement> findElements(T driver, BiFunction<String, String, List<WebElement>> finder) {
  return finder.apply("name", name);
}
 
Example 19
Source File: BunchedMapScanTest.java    From fdb-record-layer with Apache License 2.0 4 votes vote down vote up
private void testScanMulti(int limit, boolean reverse, List<List<Tuple>> keyLists,
                           @Nonnull BiFunction<Transaction,byte[],BunchedMapMultiIterator<Tuple,Tuple,Long>> iteratorFunction) {
    try (Transaction tr = db.createTransaction()) {
        byte[] continuation = null;
        List<BunchedMapScanEntry<Tuple,Tuple,Long>> entryList = new ArrayList<>();
        BunchedMapScanEntry<Tuple,Tuple,Long> lastEntry = null;
        do {
            BunchedMapMultiIterator<Tuple,Tuple,Long> iterator = iteratorFunction.apply(tr, continuation);
            int returned = 0;
            while (iterator.hasNext()) {
                BunchedMapScanEntry<Tuple,Tuple,Long> toAdd = iterator.peek();
                assertEquals(toAdd, iterator.next());
                if (lastEntry != null) {
                    if (toAdd.getSubspaceTag().equals(lastEntry.getSubspaceTag())) {
                        assertEquals(reverse ? 1 : -1, lastEntry.getKey().compareTo(toAdd.getKey()));
                    } else {
                        assertEquals(reverse ? 1 : -1, lastEntry.getSubspaceTag().compareTo(toAdd.getSubspaceTag()));
                    }
                }
                entryList.add(toAdd);
                lastEntry = toAdd;
                returned++;
            }
            continuation = iterator.getContinuation();
            if (limit == ReadTransaction.ROW_LIMIT_UNLIMITED || returned < limit) {
                assertNull(continuation);
            } else {
                assertNotNull(continuation);
            }
        } while (continuation != null);
        if (reverse) {
            entryList = Lists.reverse(entryList);
        }
        Long tag = null;
        int pos = 0;
        int totalRead = 0;
        for (BunchedMapScanEntry<Tuple,Tuple,Long> entry : entryList) {
            if (tag == null || !tag.equals(entry.getSubspaceTag())) {
                if (tag != null) {
                    assertEquals(tag + 1, entry.getSubspaceTag().longValue());
                }
                tag = entry.getSubspaceTag();
                pos = 0;
            }
            assertEquals(keyLists.get(tag.intValue()).get(pos), entry.getKey());
            assertEquals(value, entry.getValue());
            assertEquals(subSubspaces.get(tag.intValue()), entry.getSubspace());
            pos++;
            totalRead++;
        }
        int totalToSee = keyLists.stream().mapToInt(List::size).sum();
        assertEquals(totalToSee, totalRead);
    }
}
 
Example 20
Source File: CReferenceTest.java    From commons-numbers with Apache License 2.0 3 votes vote down vote up
/**
 * Assert the operation on the complex numbers is equal to the expected value.
 *
 * <p>The results are considered equal within the provided units of least
 * precision. The maximum count of numbers allowed between the two values is
 * {@code maxUlps - 1}.
 *
 * <p>Numbers must have the same sign. Thus -0.0 and 0.0 are never equal.
 *
 * @param c1 First number.
 * @param c2 Second number.
 * @param name the operation name
 * @param operation the operation
 * @param expected Expected real part.
 * @param maxUlps the maximum units of least precision between the two values
 */
static void assertComplex(Complex c1, Complex c2,
        String name, BiFunction<Complex, Complex, Complex> operation,
        Complex expected, long maxUlps) {
    final Complex z = operation.apply(c1, c2);
    assertEquals(() -> c1 + "." + name + c2 + ": real", expected.real(), z.real(), maxUlps);
    assertEquals(() -> c1 + "." + name + c2 + ": imaginary", expected.imag(), z.imag(), maxUlps);
}