Example usage for java.util Map putIfAbsent

List of usage examples for java.util Map putIfAbsent

Introduction

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

Prototype

default V putIfAbsent(K key, V value) 

Source Link

Document

If the specified key is not already associated with a value (or is mapped to null ) associates it with the given value and returns null , else returns the current value.

Usage

From source file:co.paralleluniverse.photon.Photon.java

private static void markError(final Meter errorsMeter, final Map<String, AtomicInteger> errors,
        final Throwable t) {
    errorsMeter.mark();//from w w w .  ja v a2 s  .c o m
    if (t != null) {
        errors.putIfAbsent(t.getClass().getName(), new AtomicInteger());
        errors.get(t.getClass().getName()).incrementAndGet();
    }
}

From source file:org.codice.ddf.registry.schemabindings.RegistryPackageUtils.java

public static Map<String, List<SlotType1>> getNameSlotMapDuplicateSlotNamesAllowed(List<SlotType1> slots) {
    Map<String, List<SlotType1>> slotMap = new HashMap<>();

    for (SlotType1 slot : slots) {
        slotMap.putIfAbsent(slot.getName(), new ArrayList<>());
        slotMap.get(slot.getName()).add(slot);
    }/*from  ww w .  ja v a 2  s. co m*/

    return slotMap;
}

From source file:org.apache.cassandra.schema.CompactionParams.java

public static CompactionParams create(Class<? extends AbstractCompactionStrategy> klass,
        Map<String, String> options) {
    boolean isEnabled = options.containsKey(Option.ENABLED.toString())
            ? Boolean.parseBoolean(options.get(Option.ENABLED.toString()))
            : DEFAULT_ENABLED;//from  w ww  .j  a  v  a 2s  .c o m

    Map<String, String> allOptions = new HashMap<>(options);
    if (supportsThresholdParams(klass)) {
        allOptions.putIfAbsent(Option.MIN_THRESHOLD.toString(), Integer.toString(DEFAULT_MIN_THRESHOLD));
        allOptions.putIfAbsent(Option.MAX_THRESHOLD.toString(), Integer.toString(DEFAULT_MAX_THRESHOLD));
    }

    return new CompactionParams(klass, allOptions, isEnabled);
}

From source file:org.apdplat.superword.extract.PartOfSpeechExtractor.java

private static Map<String, Set<String>> group(Set<Word> words) {
    Map<String, Set<String>> data = new HashMap<>();
    words.forEach(w -> {/*from   w  w  w . j  a  v  a 2s  .  co  m*/
        w.getPartOfSpeeches().forEach(pos -> {
            data.putIfAbsent(pos, new HashSet<>());
            data.get(pos).add(w.getWord());
        });
    });
    return data;
}

From source file:org.lightjason.agentspeak.action.buildin.graph.CAdjacencyMatrix.java

/**
 * converts a graph into an adjacency matrix
 *
 * @param p_graph graph//ww w.ja v  a2  s  . c om
 * @param p_cost map with edges and costs
 * @param p_defaultcost default cost value (on non-existing map values)
 * @param p_type matrix type
 * @return pair of double matrix and vertices
 */
private static Pair<DoubleMatrix2D, Collection<?>> apply(final AbstractGraph<Object, Object> p_graph,
        final Map<?, Number> p_cost, final double p_defaultcost, final EType p_type) {
    // index map for matching vertex to index position within matrix
    final Map<Object, Integer> l_index = new HashMap<>();

    // extract vertices from edges
    p_graph.getEdges().stream().map(p_graph::getEndpoints).flatMap(i -> Stream.of(i.getFirst(), i.getSecond()))
            .forEach(i -> l_index.putIfAbsent(i, 0));

    // define for each vertex an index number in [0, size)
    StreamUtils.zip(l_index.keySet().stream(), IntStream.range(0, l_index.size()).boxed(), ImmutablePair::new)
            .forEach(i -> l_index.put(i.getKey(), i.getValue()));

    final DoubleMatrix2D l_matrix;
    switch (p_type) {
    case SPARSE:
        l_matrix = new SparseDoubleMatrix2D(l_index.size(), l_index.size());
        break;

    default:
        l_matrix = new DenseDoubleMatrix2D(l_index.size(), l_index.size());
    }

    // map costs to matrix
    p_graph.getEdges().stream()
            .map(i -> new ImmutablePair<>(p_graph.getEndpoints(i),
                    p_cost.getOrDefault(i, p_defaultcost).doubleValue()))
            .forEach(i -> l_matrix.setQuick(l_index.get(i.getLeft().getFirst()),
                    l_index.get(i.getLeft().getSecond()),
                    i.getRight() + l_matrix.getQuick(l_index.get(i.getLeft().getFirst()),
                            l_index.get(i.getLeft().getSecond()))));

    return new ImmutablePair<>(l_matrix, new ArrayList<>(l_index.keySet()));
}

From source file:org.lightjason.agentspeak.action.builtin.graph.CAdjacencyMatrix.java

/**
 * converts a graph into an adjacency matrix
 *
 * @param p_graph graph/*w  w w.  j av  a 2s  .  c  om*/
 * @param p_cost map with edges and costs
 * @param p_defaultcost default cost value (on non-existing map values)
 * @param p_type matrix type
 * @return pair of double matrix and vertices
 */
private static Pair<DoubleMatrix2D, Collection<?>> apply(@Nonnull final Graph<Object, Object> p_graph,
        @Nonnull final Map<?, Number> p_cost, final double p_defaultcost, @Nonnull final EType p_type) {
    // index map for matching vertex to index position within matrix
    final Map<Object, Integer> l_index = new HashMap<>();

    // extract vertices from edges
    p_graph.getEdges().stream().map(p_graph::getEndpoints).flatMap(i -> Stream.of(i.getFirst(), i.getSecond()))
            .forEach(i -> l_index.putIfAbsent(i, 0));

    // define for each vertex an index number in [0, size)
    StreamUtils.zip(l_index.keySet().stream(), IntStream.range(0, l_index.size()).boxed(), ImmutablePair::new)
            .forEach(i -> l_index.put(i.getKey(), i.getValue()));

    final DoubleMatrix2D l_matrix;
    switch (p_type) {
    case SPARSE:
        l_matrix = new SparseDoubleMatrix2D(l_index.size(), l_index.size());
        break;

    default:
        l_matrix = new DenseDoubleMatrix2D(l_index.size(), l_index.size());
    }

    // map costs to matrix
    p_graph.getEdges().stream()
            .map(i -> new ImmutablePair<>(p_graph.getEndpoints(i),
                    p_cost.getOrDefault(i, p_defaultcost).doubleValue()))
            .forEach(i -> l_matrix.setQuick(l_index.get(i.getLeft().getFirst()),
                    l_index.get(i.getLeft().getSecond()),
                    i.getRight() + l_matrix.getQuick(l_index.get(i.getLeft().getFirst()),
                            l_index.get(i.getLeft().getSecond()))));

    // on undirected graphs, add the transposefor cost duplicating
    if (p_graph instanceof UndirectedGraph<?, ?>)
        l_matrix.assign(IAlgebra.ALGEBRA.transpose(l_matrix).copy(), Functions.plus);

    return new ImmutablePair<>(l_matrix, new ArrayList<>(l_index.keySet()));
}

From source file:org.fcrepo.camel.processor.EventProcessor.java

@SuppressWarnings("unchecked")
private static Map<String, List<String>> getValuesFromMap(final Map body) {
    final Map<String, Object> values = (Map<String, Object>) body;
    final Map<String, List<String>> data = new HashMap<>();
    if (values.containsKey("@id")) {
        data.put(FCREPO_URI, singletonList((String) values.get("@id")));
    }//from   w  w w. j a va 2  s.c o m
    if (values.containsKey("id")) {
        data.putIfAbsent(FCREPO_URI, singletonList((String) values.get("id")));
    }

    if (values.containsKey("@type")) {
        data.put(FCREPO_RESOURCE_TYPE, (List<String>) values.get("@type"));
    }
    if (values.containsKey("type")) {
        data.putIfAbsent(FCREPO_RESOURCE_TYPE, (List<String>) values.get("type"));
    }

    final Map<String, Object> wasGeneratedBy = (Map<String, Object>) values.get("wasGeneratedBy");

    if (wasGeneratedBy != null) {
        if (wasGeneratedBy.containsKey("type")) {
            data.put(FCREPO_EVENT_TYPE, (List<String>) wasGeneratedBy.get("type"));
        }
        data.put(FCREPO_EVENT_ID, singletonList((String) wasGeneratedBy.get("identifier")));
        data.put(FCREPO_DATE_TIME, singletonList((String) wasGeneratedBy.get("atTime")));
    }

    final List<Map<String, String>> wasAttributedTo = (List<Map<String, String>>) values.get("wasAttributedTo");
    if (wasAttributedTo != null) {
        data.put(FCREPO_AGENT, wasAttributedTo.stream().map(agent -> agent.get("name")).collect(toList()));
    }

    return data;
}

From source file:org.apdplat.superword.extract.HyphenExtractor.java

public static void extract(String allPath, String wordPath, String htmlPath, boolean verify) {
    Map<String, AtomicInteger> data = parse("/Users/apple/?/origin_html.zip");
    Map<String, AtomicInteger> wordsIT = parse("src/main/resources/it");
    wordsIT.keySet().forEach(k -> {//from ww w. j  a va2  s.c o m
        data.putIfAbsent(k, new AtomicInteger());
        data.get(k).addAndGet(wordsIT.get(k).get());
    });
    Map<String, AtomicInteger> wordsJDK = parse(
            "/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/src.zip");
    wordsJDK.keySet().forEach(k -> {
        data.putIfAbsent(k, new AtomicInteger());
        data.get(k).addAndGet(wordsJDK.get(k).get());
    });
    try {
        Files.write(Paths.get(allPath),
                data.entrySet().stream().sorted((a, b) -> b.getValue().get() - a.getValue().get())
                        .map(e -> e.getValue() + "\t" + e.getKey()).collect(Collectors.toList()));
        List<String> result = data.entrySet().stream().sorted((a, b) -> b.getValue().get() - a.getValue().get())
                .filter(e -> {
                    if (verify) {
                        return verify(e.getKey());
                    }
                    return true;
                }).map(e -> e.getValue() + "\t" + e.getKey()).collect(Collectors.toList());
        Files.write(Paths.get(wordPath), result);
        List<String> forHtmlResult = result.stream().map(s -> {
            String[] attr = s.split("\t");
            return WordLinker.toLink(attr[1]) + "(" + attr[0] + ")";
        }).collect(Collectors.toList());
        Files.write(Paths.get(htmlPath), HtmlFormatter.toHtmlTableFragment(forHtmlResult, 3).getBytes("utf-8"));
        LOGGER.info("?");
    } catch (Exception e) {
        LOGGER.error("?", e);
    }
}

From source file:org.apdplat.superword.rule.TextAnalysis.java

/**
 *  {? : ?} ?{? : ??10?}/*from   w  ww  .j a  v a2  s  .co m*/
 * @param data ?
 * @return ?
 */
public static Map<Integer, Stat> distribute(Map<String, AtomicInteger> data) {
    Map<Integer, Stat> stat = new HashMap<>();
    data.entrySet().forEach(entry -> {
        Integer key = entry.getValue().get();
        stat.putIfAbsent(key, new Stat());
        stat.get(key).increment();
        stat.get(key).addWords(entry.getKey());
    });
    return stat;
}

From source file:org.apdplat.superword.tools.HtmlFormatter.java

public static String toHtmlForWordDefinition(Set<Word> words, int rowLength) {
    Map<Integer, AtomicInteger> map = new HashMap<>();
    words.stream().forEach(w -> {/*from   w  w w .j a va  2s . co m*/
        int count = w.getDefinitions().size();
        map.putIfAbsent(count, new AtomicInteger());
        map.get(count).incrementAndGet();
    });
    List<String> data = words.stream().sorted((a, b) -> b.getDefinitions().size() - a.getDefinitions().size())
            .map(word -> WordLinker.toLink(word.getWord()) + "-" + word.getDefinitions().size())
            .collect(Collectors.toList());
    StringBuilder html = new StringBuilder();
    html.append(toHtmlTableFragment(data, rowLength)).append("<table border=\"1\">\n")
            .append("\t<tr><td>?</td><td>??</td></tr>\n");
    map.keySet().stream().sorted((a, b) -> b - a).forEach(key -> {
        html.append("\t<tr><td>").append(key).append("</td><td>").append(map.get(key)).append("</td></tr>\n");
    });
    html.append("</table>\n");
    return html.toString();
}