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:cc.kave.commons.pointsto.evaluation.runners.ProjectStoreRunner.java

private static void methodPropabilities(Collection<ICoReTypeName> types, ProjectUsageStore store)
        throws IOException {
    ICoReTypeName stringType = Iterables.find(types, t -> t.getClassName().equals("String"));

    Map<ICoReMethodName, Integer> methods = new HashMap<>();
    for (Usage usage : store.load(stringType)) {
        for (CallSite cs : usage.getReceiverCallsites()) {
            Integer currentCount = methods.getOrDefault(cs.getMethod(), 0);
            methods.put(cs.getMethod(), currentCount + 1);
        }/*from   www  . j  av  a  2 s . co m*/
    }

    double total = methods.values().stream().mapToInt(i -> i).sum();
    List<Map.Entry<ICoReMethodName, Integer>> methodEntries = new ArrayList<>(methods.entrySet());
    methodEntries
            .sort(Comparator.<Map.Entry<ICoReMethodName, Integer>>comparingInt(e -> e.getValue()).reversed());
    double mrr = 0;
    double rank = 1.0;
    for (Map.Entry<ICoReMethodName, Integer> method : methodEntries) {
        double probability = method.getValue() / total;
        mrr += probability * (1.0 / rank);
        ++rank;
        System.out.printf(Locale.US, "%s\t%.3f\n", method.getKey().getName(), probability);
    }
    System.out.println(mrr);
}

From source file:org.grouplens.samantha.modeler.featurizer.FeatureExtractorUtilities.java

static public Map<String, Integer> getTermFreq(Analyzer analyzer, String text, String termField) {
    TokenStream ts = analyzer.tokenStream(termField, text);
    Map<String, Integer> termFreq = new HashMap<>();
    try {//from   w  w  w .ja v  a 2  s  .co  m
        ts.reset();
        while (ts.incrementToken()) {
            String term = ts.reflectAsString(false);
            int cnt = termFreq.getOrDefault(term, 0);
            termFreq.put(term, cnt + 1);
        }
        ts.close();
    } catch (IOException e) {
        logger.error("{}", e.getMessage());
        throw new BadRequestException(e);
    }
    return termFreq;
}

From source file:org.xlrnet.metadict.core.util.BilingualDictionaryUtils.java

public static void sortDictionaryListAlphabetically(List<BilingualDictionary> dictionaries) {
    Map<Language, Integer> languagePriorityMap = new HashMap<>();

    // Count how often each language is used
    for (BilingualDictionary dictionary : dictionaries) {
        languagePriorityMap.put(dictionary.getSource(),
                (languagePriorityMap.getOrDefault(dictionary.getSource(), 0) + 1));
        if (dictionary.isBidirectional()) {
            languagePriorityMap.put(dictionary.getTarget(),
                    (languagePriorityMap.getOrDefault(dictionary.getTarget(), 0) + 1));
        }//from   ww  w.  ja va 2  s  .  c  o  m
    }

    // Use inverted dictionaries if the output language has a higher priority than the input language
    for (int i = 0; i < dictionaries.size(); i++) {
        BilingualDictionary dictionary = dictionaries.get(i);
        if (!dictionary.isBidirectional()) {
            continue;
        }
        int inputPriority = languagePriorityMap.get(dictionary.getSource());
        int outputPriority = languagePriorityMap.get(dictionary.getTarget());

        if (outputPriority > inputPriority) {
            dictionaries.set(i, BilingualDictionary.inverse(dictionary));
        }
    }

    Collections.sort(dictionaries);
}

From source file:com.linecorp.armeria.server.docs.ThriftDocString.java

@VisibleForTesting
static Map<String, String> getDocStringsFromJsonResource(ClassLoader classLoader, String jsonResourcePath) {
    ImmutableMap.Builder<String, String> docStrings = ImmutableMap.builder();
    try (InputStream in = classLoader.getResourceAsStream(jsonResourcePath)) {
        if (in == null) {
            throw new IllegalStateException("not found: " + jsonResourcePath);
        }//  w  ww.  j av  a 2 s.c  o m

        final Map<String, Object> json = new ObjectMapper().readValue(in, JSON_VALUE_TYPE);
        @SuppressWarnings("unchecked")
        final Map<String, Object> namespaces = (Map<String, Object>) json.getOrDefault("namespaces",
                ImmutableMap.of());
        final String packageName = (String) namespaces.get("java");
        json.forEach((key, children) -> {
            if (children instanceof Collection) {
                ((Collection) children).forEach(grandChild -> {
                    traverseChildren(docStrings, packageName, FQCN_DELIM, grandChild);
                });
            }
        });

        return docStrings.build();
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.haulmont.cuba.core.entity.LocaleHelper.java

public static String getLocalizedEnumeration(String enumerationValues, String localeBundle) {
    String result = null;//from  w  w  w .  j  a  v a2 s  . c  om
    if (StringUtils.isNotEmpty(localeBundle)) {
        Properties localeProperties = loadProperties(localeBundle);
        if (localeProperties != null) {

            Locale locale = AppBeans.get(UserSessionSource.class).getLocale();
            String key = locale.getLanguage();
            if (StringUtils.isNotEmpty(locale.getCountry())) {
                key += "_" + locale.getCountry();
            }

            List<String> enumValues = new ArrayList<>();

            String[] enumerationValuesArray = enumerationValues.split(",");
            Map<String, String> localizedValuesMap = LocaleHelper.getLocalizedValuesMap(localeBundle);
            for (String value : enumerationValuesArray) {
                String resultValue = localizedValuesMap.getOrDefault(key + "/" + value, value);
                enumValues.add(resultValue);
            }
            result = Joiner.on(",").join(enumValues);
        }
    }
    return result;
}

From source file:edu.umd.umiacs.clip.tools.classifier.LibSVMUtils.java

public static Map<Integer, Double> sum(Map<Integer, Double> map1, Map<Integer, Double> map2) {
    Map<Integer, Double> map = new HashMap<>(map1);
    map2.entrySet().stream()/*from w  w  w.j a  va  2 s .  c  o m*/
            .forEach(entry -> map.put(entry.getKey(), entry.getValue() + map.getOrDefault(entry.getKey(), 0d)));
    return map;
}

From source file:SocialRec.UserAgent.java

public static Map userAgentUtilityFunction(Map recommendedItems) {
    List<String> utilityValues = new ArrayList<>();
    Map idPersoanlUtilityValue = new HashMap();

    for (int i = 0; i < recommendedItems.size(); i++) {
        //personal
        Double vPersonalValue = Double.parseDouble((String) recommendedItems.get(i));
        Double vId = Double.parseDouble((String) recommendedItems.getOrDefault(i, vPersonalValue));
        Double vReward = Double.parseDouble((String) recommendedItems.getOrDefault(i, vPersonalValue));
        //calculate personal and reward 
        Double utilityValueReward = vPersonalValue + vReward;
        //add to persoanl list and map with id
        utilityValues.add(String.valueOf(utilityValueReward));
        idPersoanlUtilityValue.put(vId, utilityValueReward);
    }//ww w.  j a  v  a 2 s .  c  o  m
    return idPersoanlUtilityValue;

}

From source file:org.apache.metron.elasticsearch.utils.ElasticsearchUtils.java

/**
 * Constructs ES transport client from the provided ES settings additional es config
 *
 * @param settings client settings//from  www . j  av  a  2s . com
 * @param esSettings client type to instantiate
 * @return client with provided settings
 */
private static TransportClient createTransportClient(Settings settings, Map<String, String> esSettings) {
    String esClientClassName = (String) esSettings.getOrDefault("es.client.class", ES_CLIENT_CLASS_DEFAULT);
    return ReflectionUtils.createInstance(esClientClassName, new Class[] { Settings.class, Class[].class },
            new Object[] { settings, new Class[0] });
}

From source file:org.apache.tinkerpop.gremlin.spark.process.computer.traversal.strategy.optimization.SparkInterceptorStrategyTest.java

private static <R> void test(Class<? extends VertexProgramInterceptor> expectedInterceptor, R expectedResult,
        final Traversal<?, R> traversal) throws Exception {
    final Traversal.Admin<?, ?> clone = traversal.asAdmin().clone();
    clone.applyStrategies();//from  w  ww  . ja  va2s . com
    final Map<String, Object> configuration = TraversalHelper
            .getFirstStepOfAssignableClass(TraversalVertexProgramStep.class, clone).get().getComputer()
            .getConfiguration();
    final String interceptor = (String) configuration
            .getOrDefault(Constants.GREMLIN_HADOOP_VERTEX_PROGRAM_INTERCEPTOR, null);
    if (null == expectedInterceptor) {
        assertNull(interceptor);
        assertFalse((Boolean) configuration.getOrDefault(Constants.GREMLIN_SPARK_SKIP_PARTITIONER, false));
        assertFalse((Boolean) configuration.getOrDefault(Constants.GREMLIN_SPARK_SKIP_PARTITIONER, false));
    } else {
        assertEquals(expectedInterceptor, Class.forName(interceptor));
        if (interceptor.equals(SparkStarBarrierInterceptor.class.getCanonicalName())) {
            assertTrue((Boolean) configuration.getOrDefault(Constants.GREMLIN_SPARK_SKIP_PARTITIONER, false));
            assertTrue((Boolean) configuration.getOrDefault(Constants.GREMLIN_SPARK_SKIP_PARTITIONER, false));
        }
    }
    assertEquals(expectedResult, traversal.next());
}

From source file:org.apache.metron.elasticsearch.utils.ElasticsearchUtils.java

private static Map<String, String> getEsSettings(Map<String, Object> config) {
    return ConversionUtils.convertMap(
            (Map<String, Object>) config.getOrDefault("es.client.settings", new HashMap<String, Object>()),
            String.class);
}