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:org.n52.iceland.ogc.swes.OfferingExtensionRepository.java

/**
 * Get map with {@link ServiceOperatorKey} and linked domain values
 *
 * @return the map with {@link ServiceOperatorKey} and linked domain values
 *//*from www . j a va2 s .  c o  m*/
public Map<ServiceOperatorKey, Collection<String>> getAllDomains() {
    Map<ServiceOperatorKey, Collection<String>> domains = Maps.newHashMap();
    Activatables.activatedKeys(this.offeringExtensionProviders, this.activation).stream().forEach(key -> {
        domains.computeIfAbsent(key.getServiceOperatorKey(), sok -> new LinkedList<>()).add(key.getDomain());
    });
    return domains;
}

From source file:org.shredzone.commons.view.manager.ViewManager.java

/**
 * Processes a {@link View}. A view name and view pattern is generated, and a
 * {@link ViewInvoker} is built.//from   w  ww  . j  a v  a 2  s . co m
 *
 * @param bean
 *            Spring bean to be used
 * @param method
 *            View handler method to be invoked
 * @param anno
 *            {@link View} annotation
 */
private void processView(Object bean, Method method, View anno) {
    String name = computeViewName(method, anno);

    Map<String, List<ViewPattern>> vpMap = patternMap.computeIfAbsent(name, it -> new HashMap<>());

    ViewInvoker invoker = new ViewInvoker(bean, method, conversionService);
    ViewPattern vp = new ViewPattern(anno, invoker);

    List<ViewPattern> vpList = vpMap.computeIfAbsent(vp.getQualifier(), it -> new ArrayList<>());
    vpList.add(vp);

    Signature sig = vp.getSignature();
    if (sig != null) {
        Map<Signature, ViewPattern> sigMap = signatureMap.computeIfAbsent(vp.getQualifier(),
                it -> new HashMap<>());
        if (sigMap.putIfAbsent(sig, vp) != null) {
            throw new IllegalStateException("Signature '" + sig + "' defined twice");
        }
    }

    patternOrder.add(vp);

    log.info("Found view '{}' with pattern '{}'", name, anno.pattern());
}

From source file:pl.edu.icm.comac.vis.server.DataController.java

private Map<String, Double> calculateImportance(Map<URI, Map<String, Object>> nodes, Set<Link> links) {
    Set<String> others = nodes.entrySet().stream().filter(e -> !e.getValue().containsKey(JSON_FAVOURITE))
            .map(e -> e.getKey().stringValue()).collect(Collectors.toSet());
    Set<String> favs = nodes.entrySet().stream().filter(e -> e.getValue().containsKey(JSON_FAVOURITE))
            .map(e -> e.getKey().stringValue()).collect(Collectors.toSet());
    Map<String, int[]> linkCount = new HashMap<>(); //0-fav, 1-other
    for (Link link : links) {
        int idx = favs.contains(link.getTargetId()) ? 0 : 1;
        linkCount.computeIfAbsent(link.getSourceId(), x -> new int[2])[idx]++;
        idx = favs.contains(link.getSourceId()) ? 0 : 1;
        linkCount.computeIfAbsent(link.getTargetId(), x -> new int[2])[idx]++;
    }/* ww w  .  ja va  2 s  .  c o  m*/
    //now recalculate importance:
    Map<String, Double> res = new HashMap<>();
    //favs: 
    for (String f : favs) {
        int[] lc = linkCount.computeIfAbsent(f, x -> new int[2]);
        int l = lc[0] + lc[1] - 2;
        if (l < 1) {
            l = 1;
        }
        res.put(f, 1. + 0.7 * (1. - 1. / l));
    }
    for (String other : others) {
        int[] lc = linkCount.computeIfAbsent(other, x -> new int[2]);
        int l = 2 * lc[0] + lc[1] - 1;
        if (l < 1) {
            l = 1;
        }
        res.put(other, 0.7 + 0.7 * (1. - 1. / l));
    }
    return res;
}

From source file:jgnash.report.pdf.Report.java

public static Set<GroupInfo> getGroups(final AbstractReportTableModel tableModel) {
    final Map<String, GroupInfo> groupInfoMap = new HashMap<>();

    for (int c = 0; c < tableModel.getColumnCount(); c++) {
        final ColumnStyle columnStyle = tableModel.getColumnStyle(c);

        if (columnStyle == ColumnStyle.GROUP || columnStyle == ColumnStyle.GROUP_NO_HEADER) {
            for (int r = 0; r < tableModel.getRowCount(); r++) {
                final GroupInfo groupInfo = groupInfoMap.computeIfAbsent(tableModel.getValueAt(r, c).toString(),
                        GroupInfo::new);

                groupInfo.rows++;//from  w w w. java  2s .  c o m
            }
        }
    }

    // create a default group for tables that do not specify one
    if (groupInfoMap.isEmpty()) {
        GroupInfo groupInfo = new GroupInfo(DEFAULT_GROUP);
        groupInfo.rows = tableModel.getRowCount();

        groupInfoMap.put(DEFAULT_GROUP, groupInfo);
    }

    // perform summation
    for (int r = 0; r < tableModel.getRowCount(); r++) {
        final GroupInfo groupInfo = groupInfoMap.get(tableModel.getGroup(r));

        for (int c = 0; c < tableModel.getColumnCount(); c++) {
            if (tableModel.getColumnClass(c) == BigDecimal.class) {
                switch (tableModel.getColumnStyle(c)) {
                case AMOUNT_SUM:
                case BALANCE_WITH_SUM:
                case BALANCE_WITH_SUM_AND_GLOBAL:
                    groupInfo.addValue(c, (BigDecimal) tableModel.getValueAt(r, c));
                default:
                    break;
                }
            }
        }
    }

    return new TreeSet<>(groupInfoMap.values());
}

From source file:org.apache.servicecomb.foundation.vertx.http.StandardHttpServletRequestEx.java

private Map<String, List<String>> parseUrlEncodedBody() {
    try (InputStream inputStream = getInputStream()) {
        Map<String, List<String>> listMap = new HashMap<>();
        String body = IOUtils.toString(inputStream);
        List<NameValuePair> pairs = URLEncodedUtils.parse(body,
                getCharacterEncoding() == null ? null : Charset.forName(getCharacterEncoding()));
        for (NameValuePair pair : pairs) {
            List<String> values = listMap.computeIfAbsent(pair.getName(), k -> new ArrayList<>());
            values.add(pair.getValue());
        }/*  w ww.  jav a2  s.c  o  m*/
        return listMap;
    } catch (IOException e) {
        throw new IllegalStateException("", e);
    }
}

From source file:com.denkbares.semanticcore.utils.ResultTableModel.java

public Map<Value, Set<TableRow>> getData() {
    if (groupedRows == null) {
        Map<Value, Set<TableRow>> data = new LinkedHashMap<>();
        for (TableRow row : rows) {
            Value firstNode = row.getValue(variables.get(0));
            Set<TableRow> nodeRows = data.computeIfAbsent(firstNode, k -> new HashSet<>());
            nodeRows.add(row);/*  ww  w  . java 2 s  .  c  o m*/
        }
        groupedRows = data;
    }
    return groupedRows;
}

From source file:com.netflix.spinnaker.fiat.permissions.RedisPermissionsRepository.java

@Override
public RedisPermissionsRepository put(@NonNull UserPermission permission) {
    Map<ResourceType, Map<String, String>> resourceTypeToRedisValue = new HashMap<>(
            ResourceType.values().length);

    permission.getAllResources().forEach(resource -> {
        try {/*from  ww  w  .  j  ava2s .c om*/
            resourceTypeToRedisValue.computeIfAbsent(resource.getResourceType(), key -> new HashMap<>())
                    .put(resource.getName(), objectMapper.writeValueAsString(resource));
        } catch (JsonProcessingException jpe) {
            log.error("Serialization exception writing " + permission.getId() + " entry.", jpe);
        }
    });

    try (Jedis jedis = jedisSource.getJedis()) {
        Pipeline deleteOldValuesPipeline = jedis.pipelined();
        Pipeline insertNewValuesPipeline = jedis.pipelined();

        String userId = permission.getId();
        insertNewValuesPipeline.sadd(allUsersKey(), userId);

        permission.getRoles().forEach(role -> insertNewValuesPipeline.sadd(roleKey(role), userId));

        for (ResourceType r : ResourceType.values()) {
            String userResourceKey = userKey(userId, r);

            deleteOldValuesPipeline.del(userResourceKey);

            Map<String, String> redisValue = resourceTypeToRedisValue.get(r);
            if (redisValue != null && !redisValue.isEmpty()) {
                insertNewValuesPipeline.hmset(userResourceKey, redisValue);
            }
        }
        deleteOldValuesPipeline.sync();
        insertNewValuesPipeline.sync();
    } catch (Exception e) {
        log.error("Storage exception writing " + permission.getId() + " entry.", e);
    }
    return this;
}

From source file:at.gridtec.lambda4j.function.bi.BiFunction2.java

/**
 * Returns a memoized (caching) version of this {@link BiFunction2}. 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  .ja v  a2  s .  co  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 BiFunction2}.
 * @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 BiFunction2<T, U, R> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Pair<T, U>, R> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (BiFunction2<T, U, R> & Memoized) (t, u) -> {
            final R returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Pair.of(t, u), key -> apply(key.getLeft(), key.getRight()));
            }
            return returnValue;
        };
    }
}

From source file:org.eclipse.hono.deviceregistry.FileBasedCredentialsService.java

private JsonArray getAuthIdCredentials(final String authId, final Map<String, JsonArray> credentialsForTenant) {
    return credentialsForTenant.computeIfAbsent(authId, id -> new JsonArray());
}

From source file:at.gridtec.lambda4j.function.tri.TriFunction.java

/**
 * Returns a memoized (caching) version of this {@link TriFunction}. 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  va 2 s  . c om
 * 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 TriFunction}.
 * @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 TriFunction<T, U, V, R> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<T, U, V>, R> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (TriFunction<T, U, V, R> & Memoized) (t, u, v) -> {
            final R returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(t, u, v),
                        key -> apply(key.getLeft(), key.getMiddle(), key.getRight()));
            }
            return returnValue;
        };
    }
}