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.netflix.spinnaker.orca.kato.pipeline.ParallelDeployClusterExtractor.java

@Override
public List<Map> extractClusters(Map stage) {
    return (List<Map>) stage.getOrDefault("clusters", new ArrayList<Map>());
}

From source file:org.apache.storm.utils.ServerUtils.java

public static double getEstimatedTotalHeapMemoryRequiredByTopo(Map<String, Object> topoConf,
        StormTopology topology) throws InvalidTopologyException {
    Map<String, Integer> componentParallelism = getComponentParallelism(topoConf, topology);
    double totalMemoryRequired = 0.0;

    for (Map.Entry<String, Map<String, Double>> entry : ResourceUtils.getBoltsResources(topology, topoConf)
            .entrySet()) {/*from   w ww. j a  va 2  s.  c  o  m*/
        int parallelism = componentParallelism.getOrDefault(entry.getKey(), 1);
        double memoryRequirement = entry.getValue().get(Config.TOPOLOGY_COMPONENT_RESOURCES_ONHEAP_MEMORY_MB);
        totalMemoryRequired += memoryRequirement * parallelism;
    }

    for (Map.Entry<String, Map<String, Double>> entry : ResourceUtils.getSpoutsResources(topology, topoConf)
            .entrySet()) {
        int parallelism = componentParallelism.getOrDefault(entry.getKey(), 1);
        double memoryRequirement = entry.getValue().get(Config.TOPOLOGY_COMPONENT_RESOURCES_ONHEAP_MEMORY_MB);
        totalMemoryRequired += memoryRequirement * parallelism;
    }
    return totalMemoryRequired;
}

From source file:rgu.jclos.foldbuilder.FoldBuilder.java

/**
* Generates K folds and writes them to disk
* @param inputFile The CSV file from which the data comes from.
* @param outputDirectory The directory in which the folds will be written.
* @param separator The separating character in the CSV file.
* @param indexLabel The index of the labels in the CSV file. Used for stratification of the folds.
* @param k The number of folds to generates.
* @param speak Whether to print some status messages along the way.
* @return A pair containing a list of folds with ids of documents, and a dictionary that allows the user to retrieve aformentioned documents using the ids, in order to save space.
* @throws IOException If something stops the program from reading or writing the files.
*///from   w  w  w . ja v a  2s .  c  o m
private static Pair<List<Set<String>>, Map<String, Instance>> getFolds(String inputFile, String outputDirectory,
        String separator, String indexLabel, int k, boolean speak) throws IOException {
    Random rng = new Random();
    Map<String, Instance> dictionary = new HashMap<>();
    Map<String, Integer> classes = new HashMap<>();
    Map<String, List<String>> reversedDictionary = new HashMap<>();
    int id = 0;

    List<String> lines = Files.readAllLines(new File(inputFile).toPath());
    String[] elts = lines.get(0).split(separator);
    int labIndex = indexLabel.equals("first") ? 0
            : indexLabel.equals("last") ? elts.length - 1 : Integer.parseInt(indexLabel);

    for (String line : Files.readAllLines(new File(inputFile).toPath())) {
        Instance inst = new Instance();
        String[] elements = line.split(separator);
        inst.content = line;
        inst.label = elements[labIndex];
        String iid = "inst" + id;
        dictionary.put(iid, inst);
        classes.put(inst.label, classes.getOrDefault(inst.label, 0) + 1);
        if (reversedDictionary.containsKey(inst.label)) {
            reversedDictionary.get(inst.label).add(iid);
        } else {
            List<String> ids = new ArrayList<>();
            ids.add(iid);
            reversedDictionary.put(inst.label, ids);
        }
        id++;
    }

    int numberOfInstances = id;
    int sizeOfEachFold = (int) Math.floor(numberOfInstances / k);
    Map<String, Double> classRatios = new HashMap<>();
    for (Map.Entry<String, Integer> classFrequency : classes.entrySet()) {
        classRatios.put(classFrequency.getKey(),
                (double) classFrequency.getValue() / (double) numberOfInstances);
    }

    List<Set<String>> folds = new ArrayList<>();
    for (int i = 0; i < k; i++) {
        Set<String> fold = new HashSet<>();
        for (Map.Entry<String, List<String>> c : reversedDictionary.entrySet()) {
            int currentSize = fold.size();
            int numberRequired = (int) Math.floor(classRatios.get(c.getKey()) * sizeOfEachFold);
            while (fold.size() < currentSize + numberRequired && c.getValue().size() > 0) {
                int nextPick = rng.nextInt(c.getValue().size());
                fold.add(c.getValue().get(nextPick));
                c.getValue().remove(nextPick);
            }
        }
        folds.add(fold);
        if (speak)
            System.out.println("Finished computing fold " + (i + 1) + " of size " + fold.size());
    }

    if (speak)
        System.out.println("Writing folds on disk");

    return Pair.of(folds, dictionary);
}

From source file:cf.adriantodt.David.modules.rest.SetController.java

@RequestMapping("/set")
public String api(@RequestParam Map<String, String> params) {
    return api.getOrDefault(params.getOrDefault("type", ""), WebInterfaceHelper.API_CALL_NOT_FOUND)
            .apply(params).toString();/*from  w  w w. j a v a2 s  . co  m*/
}

From source file:cf.adriantodt.David.modules.rest.DoController.java

@RequestMapping("/do")
public String api(@RequestParam Map<String, String> params) {
    return api.getOrDefault(params.getOrDefault("type", ""), WebInterfaceHelper.API_CALL_NOT_FOUND)
            .apply(params).toString();/*from  ww  w .jav a 2s. co m*/
}

From source file:io.apiman.gateway.engine.threescale.ThreeScaleRequestPathParser.java

public ThreeScaleRequestPathParser(Map<String, String> config) {
    this.defaultOrgName = config.getOrDefault("defaultOrgName", ThreeScaleConstants.DEFAULT_ORGNAME);
    this.defaultVersion = config.getOrDefault("defaultVersion", ThreeScaleConstants.DEFAULT_VERSION);
}

From source file:alluxio.cli.ValidateEnv.java

private static boolean validateLocal(String target, String name, CommandLine cmd) throws InterruptedException {
    int validationCount = 0;
    Map<ValidationTask.TaskResult, Integer> results = new HashMap<>();
    Map<String, String> optionsMap = new HashMap<>();
    for (Option opt : cmd.getOptions()) {
        optionsMap.put(opt.getOpt(), opt.getValue());
    }/*from  w ww . ja va2  s .  co  m*/
    Collection<ValidationTask> tasks = TARGET_TASKS.get(target);
    System.out.format("Validating %s environment...%n", target);
    for (ValidationTask task : tasks) {
        String taskName = TASKS.get(task);
        if (name != null && !taskName.startsWith(name)) {
            continue;
        }
        System.out.format("Validating %s...%n", taskName);
        ValidationTask.TaskResult result = task.validate(optionsMap);
        results.put(result, results.getOrDefault(result, 0) + 1);
        switch (result) {
        case OK:
            System.out.print(Constants.ANSI_GREEN);
            break;
        case WARNING:
            System.out.print(Constants.ANSI_YELLOW);
            break;
        case FAILED:
            System.out.print(Constants.ANSI_RED);
            break;
        case SKIPPED:
            System.out.print(Constants.ANSI_PURPLE);
            break;
        default:
            break;
        }
        System.out.print(result.name());
        System.out.println(Constants.ANSI_RESET);
        validationCount++;
    }
    if (results.containsKey(ValidationTask.TaskResult.FAILED)) {
        System.err.format("%d failures ", results.get(ValidationTask.TaskResult.FAILED));
    }
    if (results.containsKey(ValidationTask.TaskResult.WARNING)) {
        System.err.format("%d warnings ", results.get(ValidationTask.TaskResult.WARNING));
    }
    if (results.containsKey(ValidationTask.TaskResult.SKIPPED)) {
        System.err.format("%d skipped ", results.get(ValidationTask.TaskResult.SKIPPED));
    }
    System.err.println();
    if (validationCount == 0) {
        System.err.format("No validation task matched name \"%s\".%n", name);
        return false;
    }
    if (results.containsKey(ValidationTask.TaskResult.FAILED)) {
        return false;
    }
    System.out.println("Validation succeeded.");
    return true;
}

From source file:cf.adriantodt.David.modules.rest.GetController.java

@RequestMapping("/get")
public String api(@RequestParam Map<String, String> params) {
    return api.getOrDefault(params.getOrDefault("type", ""), WebInterfaceHelper.API_CALL_NOT_FOUND)
            .apply(params).toString();/* w w  w .ja  va2s  . com*/
}

From source file:com.netflix.spinnaker.orca.mine.pipeline.CanaryPipelineClusterExtractor.java

@Override
public List<Map> extractClusters(Map stage) {
    List<Map> results = new ArrayList<>();
    List<Map> clusterPairs = (List<Map>) stage.getOrDefault("clusterPairs", new ArrayList<>());
    clusterPairs.forEach(pair -> {/*from w w w.ja v  a 2  s  .  c o  m*/
        results.add((Map) pair.get("baseline"));
        results.add((Map) pair.get("canary"));
    });
    return results;
}

From source file:it.jugtorino.one.msvc.way.rabbit.geoip.reference.service.IPLocation.java

private Map<String, Object> addGoogleMapsLink(Map<String, Object> location) {
    String googleMapsLink = "http://www.google.com/maps/place/" + location.getOrDefault("latitude", 0) + ","
            + location.getOrDefault("longitude", 0);
    location.put("google_map", googleMapsLink);
    return location;
}