Example usage for java.util Map getOrDefault

List of usage examples for java.util Map getOrDefault

Introduction

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

Prototype

default V getOrDefault(Object key, V defaultValue) 

Source Link

Document

Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

Usage

From source file:com.fortify.processrunner.processor.AbstractProcessorGroupByExpressions.java

/**
 * Add a new group entry. This will dynamically add the group entry
 * to the groups map if it does not yet exist. Depending on the
 * disk-backed map implementation, updated values may not be stored,
 * so we explicitly create a new value list and overwrite the existing
 * map entry./*  w w  w  . j a va  2s  . c om*/
 * @param context
 * @param key
 * @param value
 */
protected synchronized void addGroupEntry(Context context, String key, Object value) {
    Map<String, List<Object>> map = getGroupsMap(context);
    List<Object> cachedList = map.getOrDefault(key, new ArrayList<Object>());
    List<Object> newList = new ArrayList<Object>(cachedList);
    newList.add(value);
    map.put(key, newList);
}

From source file:edu.cmu.lti.oaqa.baseqa.answer.collective_score.scorers.EditDistanceCollectiveAnswerScorer.java

@Override
public Map<String, Double> score(JCas jcas, Answer answer) {
    Map<Answer, Double> neighbor2distance = distances.row(answer);
    ImmutableMap.Builder<String, Double> builder = ImmutableMap.builder();
    for (int topLimit : topLimits) {
        double[] distances = answers.subList(0, Math.min(answers.size(), topLimit)).stream()
                .mapToDouble(neighbor -> neighbor2distance.getOrDefault(neighbor, 0.0)).toArray();
        builder.put("edit-distance-min-" + topLimit, Doubles.min(distances));
        builder.put("edit-distance-max-" + topLimit, Doubles.max(distances));
        builder.put("edit-distance-avg-" + topLimit, DoubleStream.of(distances).average().orElse(0.0));
    }/*from   w w w  .ja v  a  2s.c  o  m*/
    return builder.build();
}

From source file:com.cognifide.qa.bb.config.YamlConfig.java

private Map<String, String> getSelectedContexts(Config rawConfig) {
    Map<String, String> contexts = new HashMap<>();
    String contextsProperty = System.getProperty(SYS_PROP_CONFIG_CONTEXTS);
    List<String> selectedContexts = StringUtils.isNotBlank(contextsProperty)
            ? Arrays.asList(contextsProperty.split(","))
            : rawConfig.getDefaultConfig().getContexts();

    Map<String, Map<String, String>> allContexts = new HashMap<>();

    allContexts.putAll(rawConfig.getContexts());
    allContexts.putAll(readAdditionalContexts());

    selectedContexts.stream()//w  w  w .j a v a2  s.  c om
            .forEach(context -> contexts.putAll(allContexts.getOrDefault(context, Collections.emptyMap())));
    return contexts;
}

From source file:io.gravitee.management.service.impl.ApiKeyServiceImpl.java

@Override
public Map<String, List<ApiKeyEntity>> findByApplication(String applicationId) {
    try {//from   w  ww .j av a 2 s  .c o m
        LOGGER.debug("Find all API keys for application {}", applicationId);

        Set<ApiKey> keys = apiKeyRepository.findByApplication(applicationId);

        Map<String, Set<ApiKey>> keysByApi = new HashMap<>();
        keys.forEach(apiKey -> {
            Set<ApiKey> values = keysByApi.getOrDefault(apiKey.getApi(), new HashSet<>());
            values.add(apiKey);
            keysByApi.put(apiKey.getApi(), values);
        });

        Map<String, List<ApiKeyEntity>> keysByApiResult = new HashMap<>(keysByApi.size());

        keysByApi.forEach((api, apiKeys) -> keysByApiResult.put(api,
                apiKeys.stream().sorted((key1, key2) -> key2.getCreatedAt().compareTo(key1.getCreatedAt()))
                        .map(ApiKeyServiceImpl::convert).collect(Collectors.toList())));

        return keysByApiResult;
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while getting all API keys for application {}", applicationId, ex);
        throw new TechnicalManagementException(
                "An error occurs while getting all API keys for application " + applicationId, ex);
    }
}

From source file:org.springframework.cloud.dataflow.server.service.impl.AppDeploymentRequestCreator.java

/**
 * Return the app instance count indicated in the provided properties.
 *
 * @param properties deployer properties for the app for which to determine the count
 * @return instance count indicated in the provided properties; if the properties do not
 * contain a count, a value of {@code 1} is returned
 *//* w w w .  j  ava  2  s  .  c  om*/
/* default */ int getInstanceCount(Map<String, String> properties) {
    return Integer.valueOf(properties.getOrDefault(AppDeployer.COUNT_PROPERTY_KEY, "1"));
}

From source file:org.codice.ddf.admin.core.impl.AdminAlertImpl.java

private void escapeStrings(Map<String, Object> map) {
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        if (entry.getValue() instanceof String) {
            entry.setValue(HtmlEscapers.htmlEscaper().escape((String) entry.getValue()));
        }/* www  .  ja v a  2 s .c o m*/
    }
    Set<String> details = (Set<String>) map.getOrDefault(Alert.SYSTEM_NOTICE_DETAILS_KEY,
            new HashSet<String>());
    Set<String> escapedStrings = new HashSet<>();
    for (String detail : details) {
        escapedStrings.add(HtmlEscapers.htmlEscaper().escape(detail));
    }
    map.put(Alert.SYSTEM_NOTICE_DETAILS_KEY, escapedStrings);
}

From source file:io.gravitee.management.service.impl.ApiKeyServiceImpl.java

@Override
public Map<String, List<ApiKeyEntity>> findByApi(String apiId) {
    try {/*from w  ww  .j av a2 s.c om*/
        LOGGER.debug("Find all API keys for API {}", apiId);

        Set<ApiKey> keys = apiKeyRepository.findByApi(apiId);

        Map<String, Set<ApiKey>> keysByApplication = new HashMap<>();
        keys.forEach(apiKey -> {
            Set<ApiKey> values = keysByApplication.getOrDefault(apiKey.getApplication(), new HashSet<>());
            values.add(apiKey);
            keysByApplication.put(apiKey.getApplication(), values);
        });

        Map<String, List<ApiKeyEntity>> keysByApplicationResult = new HashMap<>(keysByApplication.size());

        keysByApplication.forEach((api, apiKeys) -> keysByApplicationResult.put(api,
                apiKeys.stream().sorted((key1, key2) -> key2.getCreatedAt().compareTo(key1.getCreatedAt()))
                        .map(ApiKeyServiceImpl::convert).collect(Collectors.toList())));

        return keysByApplicationResult;
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while getting all API keys for API {}", apiId, ex);
        throw new TechnicalManagementException("An error occurs while getting all API keys for API " + apiId,
                ex);
    }
}

From source file:fi.hsl.parkandride.core.service.PredictionService.java

/**
 * Get the predictions by facility. Predictions that don't match the current built capacity
 * or usage of the facility are left out.
 *
 * @param facilityId the id of the facility
 * @param time the timestamp for the predictions
 * @return prediction results/*from   w w w.ja  v a2  s. c  o  m*/
 */
public List<PredictionResult> getPredictionResultByFacility(long facilityId, DateTime time) {
    final Facility facility = facilityRepository.getFacility(facilityId);

    Map<CapacityType, Set<Usage>> usagesByCapacityType = FacilityUtil.usagesByCapacityType(facility);

    return getPredictionsByFacility(facilityId, time).stream().flatMap(pb -> PredictionResult.from(pb).stream())
            .filter(pr -> usagesByCapacityType.getOrDefault(pr.capacityType, emptySet()).contains(pr.usage))
            .filter(pr -> facility.builtCapacity.getOrDefault(pr.capacityType, 0) > 0).collect(toList());
}

From source file:edu.umd.umiacs.clip.tools.scor.IndriBM25Scorer.java

@Override
public float scoreProcessed(Object query, Object text) {
    Map<String, Integer> docTerms = (Map<String, Integer>) text;
    int length = docTerms.values().stream().mapToInt(f -> f).sum();
    return (float) ((List<Pair<List<Pair<String, Float>>, Float>>) query).parallelStream()
            .mapToDouble(p -> bm25((float) p.getLeft().parallelStream()
                    .mapToDouble(pair -> pair.getRight() * docTerms.getOrDefault(pair.getLeft(), 0)).sum(),
                    p.getRight(), length))
            .sum();/*from w ww  .  j a  va 2 s  .  c om*/
}

From source file:edu.cmu.lti.oaqa.baseqa.answer.collective_score.scorers.ShapeDistanceCollectiveAnswerScorer.java

@Override
public Map<String, Double> score(JCas jcas, Answer answer) {
    ImmutableMap.Builder<String, Double> builder = ImmutableMap.builder();
    Map<Answer, Double> neighbor2distance = distances.row(answer);
    Map<Answer, Double> neighbor2bdistance = bdistances.row(answer);
    for (int topLimit : topLimits) {
        double[] distances = answers.subList(0, Math.min(answers.size(), topLimit)).stream()
                .mapToDouble(neighbor -> neighbor2distance.getOrDefault(neighbor, 0.0)).toArray();
        builder.put("shape-distance-min-" + topLimit, Doubles.min(distances));
        builder.put("shape-distance-max-" + topLimit, Doubles.max(distances));
        builder.put("shape-distance-avg-" + topLimit, DoubleStream.of(distances).average().orElse(0.0));
        double[] bdistances = answers.subList(0, Math.min(answers.size(), topLimit)).stream()
                .mapToDouble(neighbor -> neighbor2bdistance.getOrDefault(neighbor, 0.0)).toArray();
        builder.put("shape-bdistance-min-" + topLimit, Doubles.min(bdistances));
        builder.put("shape-bdistance-max-" + topLimit, Doubles.max(bdistances));
        builder.put("shape-bdistance-avg-" + topLimit, DoubleStream.of(bdistances).average().orElse(0.0));
    }//from   w w w . ja va  2s  .co m
    return builder.build();
}