Ejemplo n.º 1
0
 final V compute(
     SmoothieMap<K, V> map,
     long hash,
     K key,
     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
   long slotIndex, slot, allocIndex, storedHash = storedHash(hash);
   K k;
   V value;
   for (slotIndex = slotIndex(hash);
       (slot = readSlot(slotIndex)) != 0;
       slotIndex = nextSlotIndex(slotIndex)) {
     if (hash(slot) == storedHash
         && ((k = readKey((allocIndex = allocIndex(slot)))) == key
             || (key != null && map.keysEqual(key, k)))) {
       if ((value = remappingFunction.apply(key, this.<V>readValue(allocIndex))) != null) {
         writeValue(allocIndex, value);
         return value;
       } else {
         remove(map, slotIndex, allocIndex);
         return null;
       }
     }
   }
   if ((value = remappingFunction.apply(key, null)) != null)
     insert(map, hash, key, value, slotIndex, storedHash);
   return value;
 }
Ejemplo n.º 2
0
 @Override
 public V compute(K key, BiFunction<? super K, ? super V, ? extends V> f) {
   AHTMapEntry<K, V> e = new AHTMapEntry<>(Objects.requireNonNull(key), null);
   e =
       put(
               e,
               (k, v) -> {
                 V newValue;
                 if (v == null) {
                   newValue = f.apply(key, null);
                   if (newValue == null) {
                     return null;
                   } else {
                     return new AHTMapEntry<>(key, newValue);
                   }
                 } else {
                   newValue = f.apply(v.key, v.value);
                   if (newValue == null) {
                     return null;
                   } else {
                     return new AHTMapEntry<>(v.key, newValue);
                   }
                 }
               })
           .value;
   return e == null ? null : e.value;
 }
Ejemplo n.º 3
0
 public <KResult, VResult> MapArray<KResult, VResult> toMapArray(
     BiFunction<K, V, KResult> key, BiFunction<K, V, VResult> value) {
   MapArray<KResult, VResult> result = new MapArray<>();
   for (Pair<K, V> pair : pairs)
     result.add(key.apply(pair.key, pair.value), value.apply(pair.key, pair.value));
   return result;
 }
Ejemplo n.º 4
0
  public static void main(String[] args) {

    // (Employee e) -> e.getName();
    System.out.println("// (Employee e) -> e.getName()");
    Employee employee = new Employee("Employee Name", 8000);
    System.out.println(getName1.apply(employee));
    System.out.println(getName2.apply(employee));

    // (Employee emp,String s) -> emp.setName(s)
    System.out.println("// (Employee emp,String s) -> emp.setName(s)");
    setName1.accept(employee, "New Name 1");
    setName2.accept(employee, "New Name 2");

    // (Employee e) -> e.getName();
    System.out.println("// (Employee e) -> e.getName()");
    System.out.println(getName1.apply(employee));
    System.out.println(getName2.apply(employee));

    // (String s1, String s2) -> s1.compareTo(s2)
    System.out.println("// (String s1, String s2) -> s1.compareTo(s2)");
    System.out.println(compare1.compare("Employee", "Employee"));
    System.out.println(compare1.compare("Employee", "Employee2"));

    System.out.println(compare2.compare("Employee", "Employee"));
    System.out.println(compare2.compare("Employee", "Employee2"));

    // (Integer x, Integer y) -> Math.pow(x, y)
    System.out.println("// (Integer x, Integer y) -> Math.pow(x, y)");
    System.out.println(power1.apply(3, 4));
    System.out.println(power2.apply(5, 3));

    // (Apple a) -> a.getWeight()
    System.out.println("// (Apple a) -> a.getWeight()");
    Apple apple = new Apple(30);
    System.out.println(getWeight1.apply(apple));
    System.out.println(getWeight2.apply(apple));

    // (String x) -> Integer.parseInt(x)
    int int1 = parseInt1.apply("33");
    int int2 = parseInt1.apply("333");

    // (Employee e1, Employee e2) -> comp.compare(e1, e2)
    System.out.println("// (Employee e1, Employee e2) -> comp.compare(e1, e2)");
    Employee emp1 = new Employee("employee", 6000);
    Employee emp2 = new Employee("employee", 6000);
    System.out.println(comparator1.compare(emp1, emp2));
    System.out.println(comparator2.compare(emp1, emp2));

    setName1.accept(emp1, "new Employee");

    System.out.println(comparator1.compare(emp1, emp2));
    System.out.println(comparator2.compare(emp1, emp2));
  }
Ejemplo n.º 5
0
  /**
   * Deserializes a transaction.
   *
   * @param options The deserialization options.
   * @param deserializer The deserializer.
   * @return The deserialized transaction.
   */
  private static Transaction deserialize(
      final VerifiableEntity.DeserializationOptions options, final Deserializer deserializer) {
    final int type = deserializer.readInt("type");

    final BiFunction<VerifiableEntity.DeserializationOptions, Deserializer, Transaction>
        constructor = TYPE_TO_CONSTRUCTOR_MAP.getOrDefault(type, null);
    if (null == constructor) {
      throw new IllegalArgumentException("Unknown transaction type: " + type);
    }

    return constructor.apply(options, deserializer);
  }
Ejemplo n.º 6
0
  @Test
  public void canMultiplyWithAPolicy() {
    BiFunction<O, O, O> multiply =
        new Multiply<O, O, O>(
            new MultiplyPolicy<O, O, O>() {

              @Override
              public O multiply(O lhs, O rhs) {
                return O.YET_ANOTHER;
              }
            });
    Assert.assertEquals(O.YET_ANOTHER, multiply.apply(O.ONE, O.ANOTHER));
  }
 public IndexService newIndexService(
     NodeEnvironment environment,
     IndexService.ShardStoreDeleter shardStoreDeleter,
     NodeServicesProvider servicesProvider,
     MapperRegistry mapperRegistry,
     IndexingOperationListener... listeners)
     throws IOException {
   IndexSearcherWrapperFactory searcherWrapperFactory =
       indexSearcherWrapper.get() == null ? (shard) -> null : indexSearcherWrapper.get();
   IndexEventListener eventListener = freeze();
   final String storeType = indexSettings.getValue(INDEX_STORE_TYPE_SETTING);
   final IndexStore store;
   if (Strings.isEmpty(storeType) || isBuiltinType(storeType)) {
     store = new IndexStore(indexSettings, indexStoreConfig);
   } else {
     BiFunction<IndexSettings, IndexStoreConfig, IndexStore> factory = storeTypes.get(storeType);
     if (factory == null) {
       throw new IllegalArgumentException("Unknown store type [" + storeType + "]");
     }
     store = factory.apply(indexSettings, indexStoreConfig);
     if (store == null) {
       throw new IllegalStateException("store must not be null");
     }
   }
   indexSettings
       .getScopedSettings()
       .addSettingsUpdateConsumer(
           IndexStore.INDEX_STORE_THROTTLE_MAX_BYTES_PER_SEC_SETTING, store::setMaxRate);
   indexSettings
       .getScopedSettings()
       .addSettingsUpdateConsumer(IndexStore.INDEX_STORE_THROTTLE_TYPE_SETTING, store::setType);
   final String queryCacheType = indexSettings.getValue(INDEX_QUERY_CACHE_TYPE_SETTING);
   final BiFunction<IndexSettings, IndicesQueryCache, QueryCache> queryCacheProvider =
       queryCaches.get(queryCacheType);
   final QueryCache queryCache =
       queryCacheProvider.apply(indexSettings, servicesProvider.getIndicesQueryCache());
   return new IndexService(
       indexSettings,
       environment,
       new SimilarityService(indexSettings, similarities),
       shardStoreDeleter,
       analysisRegistry,
       engineFactory.get(),
       servicesProvider,
       queryCache,
       store,
       eventListener,
       searcherWrapperFactory,
       mapperRegistry,
       listeners);
 }
Ejemplo n.º 8
0
 static <T, U, C extends Iterable<U>, R extends Traversable<U>> R scanLeft(
     Iterable<? extends T> elements,
     U zero,
     BiFunction<? super U, ? super T, ? extends U> operation,
     C cumulativeResult,
     BiFunction<C, U, C> combiner,
     Function<C, R> finisher) {
   U acc = zero;
   cumulativeResult = combiner.apply(cumulativeResult, acc);
   for (T a : elements) {
     acc = operation.apply(acc, a);
     cumulativeResult = combiner.apply(cumulativeResult, acc);
   }
   return finisher.apply(cumulativeResult);
 }
Ejemplo n.º 9
0
  /**
   * Look-up the value through the cache. This always evaluates the {@code subKeyFactory} function
   * and optionally evaluates {@code valueFactory} function if there is no entry in the cache for
   * given pair of (key, subKey) or the entry has already been cleared.
   *
   * @param key possibly null key
   * @param parameter parameter used together with key to create sub-key and value (should not be
   *     null)
   * @return the cached value (never null)
   * @throws NullPointerException if {@code parameter} passed in or {@code sub-key} calculated by
   *     {@code subKeyFactory} or {@code value} calculated by {@code valueFactory} is null.
   */
  public V get(K key, P parameter) {
    Objects.requireNonNull(parameter);

    expungeStaleEntries();

    Object cacheKey = CacheKey.valueOf(key, refQueue);

    // lazily install the 2nd level valuesMap for the particular cacheKey
    ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
    if (valuesMap == null) {
      ConcurrentMap<Object, Supplier<V>> oldValuesMap =
          map.putIfAbsent(cacheKey, valuesMap = new ConcurrentHashMap<>());
      if (oldValuesMap != null) {
        valuesMap = oldValuesMap;
      }
    }

    // create subKey and retrieve the possible Supplier<V> stored by that
    // subKey from valuesMap
    Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
    Supplier<V> supplier = valuesMap.get(subKey);
    Factory factory = null;

    while (true) {
      if (supplier != null) {
        // supplier might be a Factory or a CacheValue<V> instance
        V value = supplier.get();
        if (value != null) {
          return value;
        }
      }
      // else no supplier in cache
      // or a supplier that returned null (could be a cleared CacheValue
      // or a Factory that wasn't successful in installing the CacheValue)

      // lazily construct a Factory
      if (factory == null) {
        factory = new Factory(key, parameter, subKey, valuesMap);
      }

      if (supplier == null) {
        supplier = valuesMap.putIfAbsent(subKey, factory);
        if (supplier == null) {
          // successfully installed Factory
          supplier = factory;
        }
        // else retry with winning supplier
      } else {
        if (valuesMap.replace(subKey, supplier, factory)) {
          // successfully replaced
          // cleared CacheEntry / unsuccessful Factory
          // with our Factory
          supplier = factory;
        } else {
          // retry with current supplier
          supplier = valuesMap.get(subKey);
        }
      }
    }
  }
Ejemplo n.º 10
0
  /**
   * Asserts that arguments can be resolved from method references for simple functional interfaces
   * that contain multiple type parameters.
   */
  public void shouldResolveMultiArgumentsForMethodRefs() {
    Baz baz = new Baz();
    BiFunction<String, Long, Integer> f1 = baz::apply;
    BiFunction<String, Long, Integer> f2 = Baz::applyStatic;
    Function3<Baz, String, Long, Integer> f3 = Baz::apply;

    assertEquals(
        TypeResolver.resolveRawArguments(BiFunction.class, f1.getClass()),
        new Class<?>[] {String.class, Long.class, Integer.class});
    assertEquals(
        TypeResolver.resolveRawArguments(BiFunction.class, f2.getClass()),
        new Class<?>[] {String.class, Long.class, Integer.class});
    assertEquals(
        TypeResolver.resolveRawArguments(Function3.class, f3.getClass()),
        new Class<?>[] {Baz.class, String.class, Long.class, Integer.class});
  }
 private OpResult addEntities(
     String query,
     Collection h,
     BiFunction<Object, PreparedStatement, PreparedStatement> setFunc) {
   Connection connection = null;
   PreparedStatement statement = null;
   try {
     connection = getJdbcConnection();
     statement = connection.prepareStatement(query);
     connection.setAutoCommit(false);
     for (Object entity : h) {
       setFunc.apply(entity, statement);
       statement.addBatch();
     }
     statement.executeBatch();
     connection.commit();
   } catch (Exception ex) {
     LOG.error("error in querying hdfs_sensitivity_entity table", ex);
   } finally {
     try {
       if (statement != null) statement.close();
       if (connection != null) connection.close();
     } catch (Exception ex) {
       LOG.error("error in closing database resources", ex);
     }
   }
   return new OpResult();
 }
  /**
   * {@inheritDoc}
   *
   * <p>This method will, on a best-effort basis, throw a {@link
   * java.util.ConcurrentModificationException} if the remapping function modified this map during
   * computation.
   *
   * @throws ConcurrentModificationException if it is detected that the remapping function modified
   *     this map
   */
  @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)) {
        int mc = modCount;
        V newValue = remappingFunction.apply(key, e.value);
        if (mc != modCount) {
          throw new ConcurrentModificationException();
        }
        if (newValue == null) {
          if (prev != null) {
            prev.next = e.next;
          } else {
            tab[index] = e.next;
          }
          modCount = mc + 1;
          count--;
        } else {
          e.value = newValue;
        }
        return newValue;
      }
    }
    return null;
  }
 private boolean getMetadata(
     String[] propertyPath, BiFunction<IndexingMetadata, Integer, Boolean> metadataFun) {
   Descriptor md = messageDescriptor;
   int i = 0;
   for (String p : propertyPath) {
     i++;
     FieldDescriptor field = md.findFieldByName(p);
     if (field == null) {
       break;
     }
     IndexingMetadata indexingMetadata =
         md.getProcessedAnnotation(IndexingMetadata.INDEXED_ANNOTATION);
     boolean res =
         indexingMetadata == null || metadataFun.apply(indexingMetadata, field.getNumber());
     if (!res) {
       break;
     }
     if (field.getJavaType() == JavaType.MESSAGE) {
       md = field.getMessageType();
     } else {
       return i == propertyPath.length;
     }
   }
   return false;
 }
 @Override
 public void forEachRemaining(Consumer<? super R> action) {
   while (left != null) {
     accept(handleLeft(), action);
   }
   if (cur == none()) {
     if (!source.tryAdvance(this)) {
       accept(pushRight(none(), none()), action);
       return;
     }
   }
   acc = mapper.apply(cur);
   source.forEachRemaining(
       next -> {
         if (!this.mergeable.test(cur, next)) {
           action.accept(acc);
           acc = mapper.apply(next);
         } else {
           acc = accumulator.apply(acc, next);
         }
         cur = next;
       });
   if (accept(pushRight(acc, cur), action)) {
     if (right != null) {
       action.accept(right.acc);
       right = null;
     }
   }
 }
Ejemplo n.º 15
0
 @Override
 public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
   Objects.requireNonNull(function);
   bulk(
       e ->
           computeIfPresent(e.key, (k, v) -> Objects.requireNonNull(function.apply(k, v)))
               == null);
 }
Ejemplo n.º 16
0
 public <T1> List<T1> select(BiFunction<K, V, T1> func) {
   try {
     return pairs.stream().map(pair -> func.apply(pair.key, pair.value)).collect(toList());
   } catch (Exception ignore) {
     throwRuntimeException(ignore);
     return new ArrayList<>();
   }
 }
Ejemplo n.º 17
0
 /**
  * Return a composed function that first applies this CheckedFunction2 to the given arguments and
  * in case of throwable try to get value from {@code recover} function with same arguments and
  * throwable information.
  *
  * @param recover the function applied in case of throwable
  * @return a function composed of this and recover
  * @throws NullPointerException if recover is null
  */
 default Function2<T1, T2, R> recover(
     Function<? super Throwable, ? extends BiFunction<? super T1, ? super T2, ? extends R>>
         recover) {
   Objects.requireNonNull(recover, "recover is null");
   return (t1, t2) -> {
     try {
       return this.apply(t1, t2);
     } catch (Throwable throwable) {
       final BiFunction<? super T1, ? super T2, ? extends R> func = recover.apply(throwable);
       Objects.requireNonNull(
           func,
           () ->
               "recover return null for " + throwable.getClass() + ": " + throwable.getMessage());
       return func.apply(t1, t2);
     }
   };
 }
Ejemplo n.º 18
0
 /**
  * Accumulates the elements of this TraversableOnce by successively calling the given function
  * {@code f} from the left, starting with a value {@code zero} of type B.
  *
  * <p>Example: Reverse and map a TraversableOnce in one pass
  *
  * <pre><code>
  * List.of("a", "b", "c").foldLeft(List.empty(), (xs, x) -&gt; xs.prepend(x.toUpperCase()))
  * // = List("C", "B", "A")
  * </code></pre>
  *
  * @param zero Value to start the accumulation with.
  * @param f The accumulator function.
  * @param <U> Result type of the accumulator.
  * @return an accumulated version of this.
  * @throws NullPointerException if {@code f} is null
  */
 default <U> U foldLeft(U zero, BiFunction<? super U, ? super T, ? extends U> f) {
   Objects.requireNonNull(f, "f is null");
   U xs = zero;
   for (T x : this) {
     xs = f.apply(xs, x);
   }
   return xs;
 }
Ejemplo n.º 19
0
 public V first(BiFunction<K, V, Boolean> func) {
   try {
     for (Pair<K, V> pair : pairs) if (func.apply(pair.key, pair.value)) return pair.value;
     return null;
   } catch (Exception ignore) {
     throwRuntimeException(ignore);
     return null;
   }
 }
  @Override
  public V compute(K key, BiFunction<K, V, V> recomputeFunction) {
    checkState(!destroyed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);
    checkNotNull(recomputeFunction, "Recompute function cannot be null");

    AtomicBoolean updated = new AtomicBoolean(false);
    AtomicReference<MapValue<V>> previousValue = new AtomicReference<>();
    MapValue<V> computedValue =
        items.compute(
            serializer.copy(key),
            (k, mv) -> {
              previousValue.set(mv);
              V newRawValue = recomputeFunction.apply(key, mv == null ? null : mv.get());
              if (mv != null && Objects.equals(newRawValue, mv.get())) {
                // value was not updated
                return mv;
              }
              MapValue<V> newValue =
                  new MapValue<>(newRawValue, timestampProvider.apply(key, newRawValue));
              if (mv == null || newValue.isNewerThan(mv)) {
                updated.set(true);
                // We return a copy to ensure updates to peers can be serialized.
                // This prevents replica divergence due to serialization failures.
                return serializer.copy(newValue);
              } else {
                return mv;
              }
            });
    if (updated.get()) {
      notifyPeers(
          new UpdateEntry<>(key, computedValue),
          peerUpdateFunction.apply(key, computedValue.get()));
      EventuallyConsistentMapEvent.Type updateType = computedValue.isTombstone() ? REMOVE : PUT;
      V value =
          computedValue.isTombstone()
              ? previousValue.get() == null ? null : previousValue.get().get()
              : computedValue.get();
      if (value != null) {
        notifyListeners(new EventuallyConsistentMapEvent<>(mapName, updateType, key, value));
      }
    }
    return computedValue.get();
  }
Ejemplo n.º 21
0
 /**
  * Returns true if the specified function is applicable for all elements in the current fuzzy
  * relation.
  *
  * @param function some boolean function.
  * @return see description.
  */
 private boolean checkAllElements(BiFunction<Double, Double, Boolean> function) {
   for (int i = 0; i < matrix.length; i++) {
     for (int j = 0; j < matrix.length; j++) {
       if (!function.apply(matrix[i][j], matrix[j][i])) {
         return false;
       }
     }
   }
   return true;
 }
Ejemplo n.º 22
0
 /**
  * Returns a result of applying the specified function for every element of the current and
  * specified fuzzy relations.
  *
  * @param anotherRelation an another fuzzy relation.
  * @param function some boolean function.
  * @return see description.
  */
 private FuzzyRelation action(
     FuzzyRelation anotherRelation, BiFunction<Double, Double, Double> function) {
   double[][] result = new double[matrix.length][matrix.length];
   for (int i = 0; i < matrix.length; i++) {
     for (int j = 0; j < matrix.length; j++) {
       result[i][j] = function.apply(matrix[i][j], anotherRelation.matrix[i][j]);
     }
   }
   return new FuzzyRelation(result);
 }
Ejemplo n.º 23
0
 public IndexService newIndexService(
     NodeEnvironment environment,
     IndexService.ShardStoreDeleter shardStoreDeleter,
     NodeServicesProvider servicesProvider)
     throws IOException {
   final IndexSettings settings = indexSettings.newWithListener(settingsConsumers);
   IndexSearcherWrapperFactory searcherWrapperFactory =
       indexSearcherWrapper.get() == null ? (shard) -> null : indexSearcherWrapper.get();
   IndexEventListener eventListener = freeze();
   final String storeType = settings.getSettings().get(STORE_TYPE);
   final IndexStore store;
   if (storeType == null || isBuiltinType(storeType)) {
     store = new IndexStore(settings, indexStoreConfig);
   } else {
     BiFunction<IndexSettings, IndexStoreConfig, IndexStore> factory = storeTypes.get(storeType);
     if (factory == null) {
       throw new IllegalArgumentException("Unknown store type [" + storeType + "]");
     }
     store = factory.apply(settings, indexStoreConfig);
     if (store == null) {
       throw new IllegalStateException("store must not be null");
     }
   }
   final String queryCacheType =
       settings.getSettings().get(IndexModule.QUERY_CACHE_TYPE, IndexModule.INDEX_QUERY_CACHE);
   final BiFunction<IndexSettings, IndicesQueryCache, QueryCache> queryCacheProvider =
       queryCaches.get(queryCacheType);
   final QueryCache queryCache =
       queryCacheProvider.apply(settings, servicesProvider.getIndicesQueryCache());
   return new IndexService(
       settings,
       environment,
       new SimilarityService(settings, similarities),
       shardStoreDeleter,
       analysisRegistry,
       engineFactory.get(),
       servicesProvider,
       queryCache,
       store,
       eventListener,
       searcherWrapperFactory);
 }
Ejemplo n.º 24
0
 public MapArray<K, V> where(BiFunction<K, V, Boolean> func) {
   try {
     return pairs
         .stream()
         .filter(pair -> func.apply(pair.key, pair.value))
         .collect(Collectors.toCollection(MapArray::new));
   } catch (Exception ignore) {
     throwRuntimeException(ignore);
     return null;
   }
 }
Ejemplo n.º 25
0
  /**
   * Postorder traversal algorithm
   *
   * @param i - start index
   * @param action - BiFunction with 1st argument -- current position, 2nd argument -- value of the
   *     tree in this position
   */
  public void postorderTraversal(int i, BiFunction action) {
    for (int j = 0; j < degree; j++) {
      int index = jthChild(i, j);
      if (get(index) != null) {
        postorderTraversal(index, action);
      }
    }
    // perform visit
    // System.out.println("tree[" + i + "] \t=\t" + tree[i]);

    action.apply(i, tree[i]);
  }
  @Override
  public void put(K key, V value) {
    checkState(!destroyed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);
    checkNotNull(value, ERROR_NULL_VALUE);

    MapValue<V> newValue = new MapValue<>(value, timestampProvider.apply(key, value));
    if (putInternal(key, newValue)) {
      notifyPeers(new UpdateEntry<>(key, newValue), peerUpdateFunction.apply(key, value));
      notifyListeners(new EventuallyConsistentMapEvent<>(mapName, PUT, key, value));
    }
  }
Ejemplo n.º 27
0
 /**
  * {@inheritDoc}
  *
  * @implSpec The default implementation is equivalent to performing the following steps for this
  *     {@code map}, then returning the current value or {@code null} if now absent. :
  *     <pre>{@code
  * if (map.get(key) != null) {
  *     V oldValue = map.get(key);
  *     V newValue = remappingFunction.apply(key, oldValue);
  *     if (newValue != null)
  *         map.replace(key, oldValue, newValue);
  *     else
  *         map.remove(key, oldValue);
  * }
  * }</pre>
  *     The default implementation may retry these steps when multiple threads attempt updates
  *     including potentially calling the remapping function multiple times.
  *     <p>This implementation assumes that the ConcurrentMap cannot contain null values and {@code
  *     get()} returning null unambiguously means the key is absent. Implementations which support
  *     null values <strong>must</strong> override this default implementation.
  * @throws UnsupportedOperationException {@inheritDoc}
  * @throws ClassCastException {@inheritDoc}
  * @throws NullPointerException {@inheritDoc}
  * @since 1.8
  */
 @Override
 default V computeIfPresent(
     K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
   Objects.requireNonNull(remappingFunction);
   V oldValue;
   while ((oldValue = get(key)) != null) {
     V newValue = remappingFunction.apply(key, oldValue);
     if (newValue != null) {
       if (replace(key, oldValue, newValue)) return newValue;
     } else if (remove(key, oldValue)) return null;
   }
   return oldValue;
 }
Ejemplo n.º 28
0
  @Override
  public <U> ImmutableMap<K, U> mapped(BiFunction<? super K, ? super V, ? extends U> mapper) {
    Object[] newValues = this.values.clone();
    int len = this.values.length;

    for (int i = 0; i < len; i++) {
      Object value = this.values[i];
      if (value != null) {
        newValues[i] = mapper.apply(this.keys[i], (V) value);
      }
    }
    return new EnumMap(this.type, this.keys, newValues, this.size);
  }
Ejemplo n.º 29
0
 final void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
   for (long a,
           tail,
           allocations = (a = ~bitSet) << (tail = Long.numberOfLeadingZeros(a)),
           allocIndex = 64 - tail;
       allocations != 0;
       allocations <<= 1, allocIndex--) {
     if (allocations < 0) {
       writeValue(
           allocIndex, function.apply(this.<K>readKey(allocIndex), this.<V>readValue(allocIndex)));
     }
   }
 }
Ejemplo n.º 30
0
 @Override
 public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> f) {
   AHTMapEntry<K, V> e =
       new AHTMapEntry<>(Objects.requireNonNull(key), Objects.requireNonNull(value));
   Objects.requireNonNull(f);
   AHTMapEntry<K, V> r =
       put(
               e,
               (k, v) -> {
                 if (v == null) {
                   return e;
                 } else {
                   V v2 = f.apply(v.value, value);
                   if (v2 == null) {
                     return null;
                   } else {
                     return new AHTMapEntry<>(key, f.apply(v.value, value));
                   }
                 }
               })
           .value;
   return r == null ? null : r.value;
 }