Example usage for java.util HashMap putIfAbsent

List of usage examples for java.util HashMap putIfAbsent

Introduction

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

Prototype

@Override
    public V putIfAbsent(K key, V value) 

Source Link

Usage

From source file:com.wormsim.utils.Utils.java

public static SimulationCommands readCommandLine(String[] p_args) throws IllegalArgumentException {
    // Convert the arguments into command lists
    HashMap<String, List<String>> data = new HashMap<>(p_args.length);
    String current_cmd = null;/*ww  w. ja  v  a2 s.  c o m*/
    for (String arg : p_args) {
        if (arg.startsWith("-")) {
            current_cmd = arg;
            if (data.putIfAbsent(arg, new ArrayList<>(2)) != null) {
                throw new IllegalArgumentException("Repeated Argument: " + arg);
            }
        } else if (current_cmd != null) {
            data.get(current_cmd).add(arg);
        } else {
            throw new IllegalArgumentException("First Parameter must be Argument: " + arg);
        }
    }
    // Check if any of the commands are something to act upon right now, like help.
    // WARNING: Hard Coded Parameters.
    if (data.containsKey("-h") || data.containsKey("--help")) {
        // Print out the help and then terminate, although the other arguments should
        // also be checked to see if they are relevant.
        help();
        System.exit(0); // Generally not recommended, but should be fine here.
        // TODO: Detailed information as per argument for help?
    }
    SimulationCommands cmds = new SimulationCommands(data);
    return cmds;
}

From source file:org.elasticsearch.test.rest.yaml.ClientYamlTestExecutionContext.java

/**
 * Calls an elasticsearch api with the parameters and request body provided as arguments.
 * Saves the obtained response in the execution context.
 *///  w  ww. ja va2 s . c  o  m
public ClientYamlTestResponse callApi(String apiName, Map<String, String> params,
        List<Map<String, Object>> bodies, Map<String, String> headers) throws IOException {
    //makes a copy of the parameters before modifying them for this specific request
    HashMap<String, String> requestParams = new HashMap<>(params);
    requestParams.putIfAbsent("error_trace", "true"); // By default ask for error traces, this my be overridden by params
    for (Map.Entry<String, String> entry : requestParams.entrySet()) {
        if (stash.containsStashedValue(entry.getValue())) {
            entry.setValue(stash.getValue(entry.getValue()).toString());
        }
    }

    HttpEntity entity = createEntity(bodies, headers);
    try {
        response = callApiInternal(apiName, requestParams, entity, headers);
        return response;
    } catch (ClientYamlTestResponseException e) {
        response = e.getRestTestResponse();
        throw e;
    } finally {
        // if we hit a bad exception the response is null
        Object responseBody = response != null ? response.getBody() : null;
        //we always stash the last response body
        stash.stashValue("body", responseBody);
    }
}

From source file:com.github.anba.es6draft.chakra.ChakraTest.java

private static Map<String, TestSetting> readSettings(Path dir) {
    Path settingsFile = dir.resolve("rlexe.xml");
    if (Files.isRegularFile(settingsFile)) {
        try (Reader reader = bomReader(Files.newInputStream(settingsFile))) {
            Document doc = Resources.xml(reader);
            NodeList elements = doc.getElementsByTagName("default");
            HashMap<String, TestSetting> settingMap = new HashMap<>();
            for (int i = 0, length = elements.getLength(); i < length; ++i) {
                Element element = (Element) elements.item(i);
                String files = element.getElementsByTagName("files").item(0).getTextContent();
                TestSetting setting = new TestSetting();
                NodeList baseline = element.getElementsByTagName("baseline");
                if (baseline.getLength() > 0) {
                    setting.baseline = baseline.item(0).getTextContent();
                }/* ww w  . ja v  a 2 s.c  o  m*/
                NodeList compileFlags = element.getElementsByTagName("compile-flags");
                if (compileFlags.getLength() > 0) {
                    String flags = compileFlags.item(0).getTextContent();
                    setting.disabled = flags.contains("-verbose") || flags.contains("-dump:")
                            || flags.contains("-trace:") || flags.contains("-testtrace:")
                            || flags.contains("-testTrace:");
                }
                settingMap.putIfAbsent(files, setting);
            }
            return settingMap;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
    return Collections.emptyMap();
}

From source file:com.wormsim.data.SimulationConditions.java

public static SimulationConditions read(String str) throws IOException {
    RealDistribution food = null;// ww w . j  a  v  a2  s .c o m
    HashMap<Integer, RealDistribution> pheromones = new HashMap<>();
    HashMap<String, IntegerDistribution> groups = new HashMap<>();

    if (Utils.MULTIBRACKET_VALIDITY_PATTERN.matcher(str).matches()) {
        Matcher m = Utils.SAMPLER_PATTERN.matcher(str);
        while (m.find()) {
            String match = m.group();
            String[] keyvalue = match.split("~");
            if (keyvalue[0].matches("\\s*food\\s*")) {
                food = Utils.readRealDistribution(keyvalue[1].trim());
            } else if (keyvalue[0].matches("\\s*pheromone\\[\\d+\\]\\s*")) {
                int leftbracket = keyvalue[0].indexOf('[') + 1;
                int rightbracket = keyvalue[0].indexOf(']');
                int id = 0;
                try {
                    id = Integer.valueOf(keyvalue[0].substring(leftbracket, rightbracket));
                    if (id < 0) {
                        throw new IOException("Invalid pheromone reference " + id + ", must be positive!");
                    }
                } catch (NumberFormatException ex) {
                    throw new IOException(ex);
                }
                if (pheromones.putIfAbsent(id, Utils.readRealDistribution(keyvalue[1].trim())) != null) {
                    throw new IOException("Duplicate pheromone id " + id);
                }
            } else { // Group Distribution
                groups.put(keyvalue[0].trim(), Utils.readIntegerDistribution(keyvalue[1].trim()));
            }
        }
    } else {
        throw new IOException("Brackets are missing on simulation conditions definition.");
    }
    if (food == null || groups.isEmpty()) {
        throw new IOException("Incomplete Data! Missing food or groups.");
    }

    // Convert pheromones into array
    Optional<Integer> max = pheromones.keySet().stream().max(Integer::max);

    RealDistribution[] pheromone_arr = new RealDistribution[max.orElse(0)];
    pheromones.forEach((k, v) -> pheromone_arr[k - 1] = v);
    for (int i = 0; i < pheromone_arr.length; i++) {
        if (pheromone_arr[i] == null) {
            pheromone_arr[i] = Utils.ZERO_REAL_DISTRIBUTION;
        }
    }

    return new SimulationConditions(food, pheromone_arr, groups);
}

From source file:beproject.MainGUI.java

TreeMap getFrequentWords() throws SQLException {
    HashMap<String, Integer> i = new HashMap<>();
    ResultSet rs = stmt/*from w  w w  .jav a2 s .  co m*/
            .executeQuery("select tweet from tweets where moviename='" + movieName + "' LIMIT 0, 10000");
    while (rs.next()) {
        String[] data = rs.getString(1).toLowerCase().split("[ \t\n\'\";?!,]");
        for (String tmp : data) {
            if (tmp.contains("http") || tmp.length() < 4)
                continue;
            Integer a = i.putIfAbsent(tmp, 1);
            if (a != null) {
                i.put(tmp, a + 1);
            }
        }
    }

    ValueComparator bvc = new ValueComparator(i);
    TreeMap<String, Integer> sorted_map = new TreeMap<>(bvc);
    sorted_map.putAll(i);
    return sorted_map;
}

From source file:org.cloudfoundry.identity.uaa.oauth.AccessController.java

private List<Map<String, String>> getScopes(ArrayList<String> scopes) {

    List<Map<String, String>> result = new ArrayList<Map<String, String>>();
    for (String scope : scopes) {
        HashMap<String, String> map = new HashMap<String, String>();
        String code = SCOPE_PREFIX + scope;
        map.put("code", code);

        Optional<ScimGroup> group = groupProvisioning.query(String.format("displayName eq \"%s\"", scope))
                .stream().findFirst();//w  w w  .  j a  va  2 s . c o m
        group.ifPresent(g -> {
            String description = g.getDescription();
            if (StringUtils.hasText(description)) {
                map.put("text", description);
            }
        });
        map.putIfAbsent("text", scope);

        result.add(map);
    }
    Collections.sort(result, (map1, map2) -> {
        String code1 = map1.get("code");
        String code2 = map2.get("code");
        int i;
        if (0 != (i = codeIsPasswordOrOpenId(code2) - codeIsPasswordOrOpenId(code1))) {
            return i;
        }
        return code1.compareTo(code2);
    });
    return result;
}