Example usage for java.util Map computeIfAbsent

List of usage examples for java.util Map computeIfAbsent

Introduction

In this page you can find the example usage for java.util Map computeIfAbsent.

Prototype

default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) 

Source Link

Document

If the specified key is not already associated with a value (or is mapped to null ), attempts to compute its value using the given mapping function and enters it into this map unless null .

Usage

From source file:at.gridtec.lambda4j.function.tri.obj.BiObjShortToDoubleFunction.java

/**
 * Returns a memoized (caching) version of this {@link BiObjShortToDoubleFunction}. Whenever it is called, the
 * mapping between the input parameters and the return value is preserved in a cache, making subsequent calls
 * returning the memoized value instead of computing the return value again.
 * <p>// w  ww  .  j  a va 2  s.  c  o  m
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code BiObjShortToDoubleFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default BiObjShortToDoubleFunction<T, U> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<T, U, Short>, Double> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (BiObjShortToDoubleFunction<T, U> & Memoized) (t, u, value) -> {
            final double returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(t, u, value),
                        key -> applyAsDouble(key.getLeft(), key.getMiddle(), key.getRight()));
            }
            return returnValue;
        };
    }
}

From source file:at.gridtec.lambda4j.function.tri.obj.BiObjBooleanToCharFunction.java

/**
 * Returns a memoized (caching) version of this {@link BiObjBooleanToCharFunction}. Whenever it is called, the
 * mapping between the input parameters and the return value is preserved in a cache, making subsequent calls
 * returning the memoized value instead of computing the return value again.
 * <p>/*from w  w  w  . j a  v  a2s . com*/
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code BiObjBooleanToCharFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default BiObjBooleanToCharFunction<T, U> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<T, U, Boolean>, Character> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (BiObjBooleanToCharFunction<T, U> & Memoized) (t, u, value) -> {
            final char returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(t, u, value),
                        key -> applyAsChar(key.getLeft(), key.getMiddle(), key.getRight()));
            }
            return returnValue;
        };
    }
}

From source file:at.gridtec.lambda4j.function.tri.obj.BiObjIntToDoubleFunction.java

/**
 * Returns a memoized (caching) version of this {@link BiObjIntToDoubleFunction}. Whenever it is called, the mapping
 * between the input parameters and the return value is preserved in a cache, making subsequent calls returning the
 * memoized value instead of computing the return value again.
 * <p>//  www .  j  av  a  2s  .c o m
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code BiObjIntToDoubleFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default BiObjIntToDoubleFunction<T, U> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<T, U, Integer>, Double> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (BiObjIntToDoubleFunction<T, U> & Memoized) (t, u, value) -> {
            final double returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(t, u, value),
                        key -> applyAsDouble(key.getLeft(), key.getMiddle(), key.getRight()));
            }
            return returnValue;
        };
    }
}

From source file:com.evolveum.midpoint.model.common.stringpolicy.ValuePolicyProcessor.java

/**
 * Count cardinality// w ww  .j  a v a2 s  .co m
 */
private Map<Integer, List<String>> cardinalityCounter(Map<StringLimitType, List<String>> lims,
        List<String> password, Boolean skipMatchedLims, boolean uniquenessReached, OperationResult op) {
    HashMap<String, Integer> counter = new HashMap<>();

    Map<StringLimitType, List<String>> mustBeFirst = new HashMap<>();
    for (Map.Entry<StringLimitType, List<String>> entry : lims.entrySet()) {
        final StringLimitType key = entry.getKey();
        int counterKey = 1;
        List<String> chars = entry.getValue();
        int i = 0;
        if (null != password) {
            i = charIntersectionCounter(entry.getValue(), password);
        }
        // If max is exceed then error unable to continue
        if (key.getMaxOccurs() != null && i > key.getMaxOccurs()) {
            OperationResult o = new OperationResult("Limitation check :" + key.getDescription());
            o.recordFatalError("Exceeded maximal value for this limitation. " + i + ">" + key.getMaxOccurs());
            op.addSubresult(o);
            return null;
            // if max is all ready reached or skip enabled for minimal skip
            // counting
        } else if (key.getMaxOccurs() != null && i == key.getMaxOccurs()) {
            continue;
            // other cases minimum is not reached
        } else if ((key.getMinOccurs() == null || i >= key.getMinOccurs()) && !skipMatchedLims) {
            continue;
        }
        for (String s : chars) {
            if (null == password || !password.contains(s) || uniquenessReached) {
                // if (null == counter.get(s)) {
                counter.put(s, counterKey);
                // } else {
                // counter.put(s, counter.get(s) + 1);
                // }
            }
        }
        counterKey++;
    }

    // If need to remove disabled chars (already reached limitations)
    if (null != password) {
        for (StringLimitType l : lims.keySet()) {
            int i = charIntersectionCounter(lims.get(l), password);
            if (l.getMaxOccurs() != null && i > l.getMaxOccurs()) {
                OperationResult o = new OperationResult("Limitation check :" + l.getDescription());
                o.recordFatalError("Exceeded maximal value for this limitation. " + i + ">" + l.getMaxOccurs());
                op.addSubresult(o);
                return null;
            } else if (l.getMaxOccurs() != null && i == l.getMaxOccurs()) {
                // limitation matched remove all used chars
                LOGGER.trace("Skip " + l.getDescription());
                for (String charToRemove : lims.get(l)) {
                    counter.remove(charToRemove);
                }
            }
        }
    }

    // Transpone to better format
    Map<Integer, List<String>> ret = new HashMap<>();
    for (String s : counter.keySet()) {
        // if not there initialize
        ret.computeIfAbsent(counter.get(s), k -> new ArrayList<>());
        ret.get(counter.get(s)).add(s);
    }
    return ret;
}

From source file:at.gridtec.lambda4j.function.tri.obj.BiObjCharToDoubleFunction.java

/**
 * Returns a memoized (caching) version of this {@link BiObjCharToDoubleFunction}. Whenever it is called, the
 * mapping between the input parameters and the return value is preserved in a cache, making subsequent calls
 * returning the memoized value instead of computing the return value again.
 * <p>/*from  w  w  w.j  a  v  a2  s.c o  m*/
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code BiObjCharToDoubleFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default BiObjCharToDoubleFunction<T, U> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<T, U, Character>, Double> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (BiObjCharToDoubleFunction<T, U> & Memoized) (t, u, value) -> {
            final double returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(t, u, value),
                        key -> applyAsDouble(key.getLeft(), key.getMiddle(), key.getRight()));
            }
            return returnValue;
        };
    }
}

From source file:at.gridtec.lambda4j.function.tri.obj.BiObjDoubleToDoubleFunction.java

/**
 * Returns a memoized (caching) version of this {@link BiObjDoubleToDoubleFunction}. Whenever it is called, the
 * mapping between the input parameters and the return value is preserved in a cache, making subsequent calls
 * returning the memoized value instead of computing the return value again.
 * <p>//from  ww  w.  ja  va2 s  .  c o  m
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code BiObjDoubleToDoubleFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default BiObjDoubleToDoubleFunction<T, U> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<T, U, Double>, Double> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (BiObjDoubleToDoubleFunction<T, U> & Memoized) (t, u, value) -> {
            final double returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(t, u, value),
                        key -> applyAsDouble(key.getLeft(), key.getMiddle(), key.getRight()));
            }
            return returnValue;
        };
    }
}

From source file:at.gridtec.lambda4j.predicate.bi.ThrowableBiPredicate.java

/**
 * Returns a memoized (caching) version of this {@link ThrowableBiPredicate}. Whenever it is called, the mapping
 * between the input parameters and the return value is preserved in a cache, making subsequent calls returning the
 * memoized value instead of computing the return value again.
 * <p>// w ww .ja v  a 2s.  c o m
 * Unless the predicate and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code ThrowableBiPredicate}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized predicate, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized predicate can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default ThrowableBiPredicate<T, U, X> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Pair<T, U>, Boolean> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (ThrowableBiPredicate<T, U, X> & Memoized) (t, u) -> {
            final boolean returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Pair.of(t, u),
                        ThrowableFunction.of(key -> testThrows(key.getLeft(), key.getRight())));
            }
            return returnValue;
        };
    }
}

From source file:at.gridtec.lambda4j.function.tri.obj.BiObjBooleanToDoubleFunction.java

/**
 * Returns a memoized (caching) version of this {@link BiObjBooleanToDoubleFunction}. Whenever it is called, the
 * mapping between the input parameters and the return value is preserved in a cache, making subsequent calls
 * returning the memoized value instead of computing the return value again.
 * <p>/* w ww .jav  a2s  .  c o m*/
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code BiObjBooleanToDoubleFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default BiObjBooleanToDoubleFunction<T, U> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<T, U, Boolean>, Double> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (BiObjBooleanToDoubleFunction<T, U> & Memoized) (t, u, value) -> {
            final double returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(t, u, value),
                        key -> applyAsDouble(key.getLeft(), key.getMiddle(), key.getRight()));
            }
            return returnValue;
        };
    }
}

From source file:com.streamsets.pipeline.stage.processor.mapper.FieldMapperProcessor.java

private void transformFieldPaths(Record record) throws StageException {
    final Map<String, List<Field>> newPathsToFields = new LinkedHashMap<>();
    final LinkedList<String> pathsToDelete = new LinkedList<>();
    final Map<Field, String> fieldsToPreviousPaths = new HashMap<>();

    record.forEachField(fv -> {/*  ww w  .j  a va 2 s.com*/
        final String fieldPath = fv.getFieldPath();
        final String fieldName = fv.getFieldName();
        final Field field = fv.getField();
        if (checkSkipFieldAndSetContextVar(fieldPath, fieldName, field, true)) {
            return;
        }
        try {
            final String newPath = mapperExpressionEval.eval(expressionVars,
                    fieldMapperConfig.mappingExpression, String.class);

            newPathsToFields.computeIfAbsent(newPath, k -> new LinkedList<>());
            newPathsToFields.get(newPath).add(field);
        } catch (ELEvalException e) {
            throw new RuntimeException(String.format("Failed to evaluate mapper expression %s: %s",
                    fieldMapperConfig.mappingExpression, e.getMessage()), e);
        }
        if (!fieldMapperConfig.maintainOriginalPaths) {
            pathsToDelete.add(fieldPath);
        }
        fieldsToPreviousPaths.put(field, fieldPath);
    });

    for (String newPath : newPathsToFields.keySet()) {
        final List<Field> mappedFields = new LinkedList<>(newPathsToFields.get(newPath));
        if (aggregationEval != null) {
            expressionVars.addVariable("fields", mappedFields);
            AggregationEL.setFieldsToPreviousPathsInContext(expressionVars, fieldsToPreviousPaths);
            final Object aggregationResult = aggregationEval.eval(expressionVars,
                    fieldMapperConfig.aggregationExpression, Object.class);
            expressionVars.addVariable("fields", null);
            if (aggregationResult instanceof Field) {
                record.set(newPath, (Field) aggregationResult);
            } else {
                final Field.Type aggregationResultType = FieldUtils.getTypeFromObject(aggregationResult);
                record.set(newPath, Field.create(aggregationResultType, aggregationResult));
            }
        } else {
            boolean replaceValues = false;
            if (record.has(newPath)) {
                final Field existingField = record.get(newPath);
                if (existingField.getType() == Field.Type.LIST) {
                    final List<Field> valueAsList = existingField.getValueAsList();
                    if (!fieldMapperConfig.appendListValues) {
                        valueAsList.clear();
                    }
                    valueAsList.addAll(mappedFields);
                } else if (fieldMapperConfig.structureChangeAllowed) {
                    replaceValues = true;
                }
            } else if (fieldMapperConfig.structureChangeAllowed) {
                replaceValues = true;
            }

            if (replaceValues) {
                if (mappedFields.size() > 1) {
                    record.set(newPath, Field.create(new LinkedList<>(mappedFields)));
                } else {
                    record.set(newPath, mappedFields.iterator().next());
                }
            }
        }
    }
    pathsToDelete.descendingIterator().forEachRemaining(path -> record.delete(path));
}

From source file:at.gridtec.lambda4j.function.tri.obj.ThrowableObjBiByteFunction.java

/**
 * Returns a memoized (caching) version of this {@link ThrowableObjBiByteFunction}. Whenever it is called, the
 * mapping between the input parameters and the return value is preserved in a cache, making subsequent calls
 * returning the memoized value instead of computing the return value again.
 * <p>/* ww  w. ja  va 2 s .  c  o m*/
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code ThrowableObjBiByteFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default ThrowableObjBiByteFunction<T, R, X> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<T, Byte, Byte>, R> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (ThrowableObjBiByteFunction<T, R, X> & Memoized) (t, value1, value2) -> {
            final R returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(t, value1, value2), ThrowableFunction
                        .of(key -> applyThrows(key.getLeft(), key.getMiddle(), key.getRight())));
            }
            return returnValue;
        };
    }
}