Example usage for java.util Map size

List of usage examples for java.util Map size

Introduction

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

Prototype

int size();

Source Link

Document

Returns the number of key-value mappings in this map.

Usage

From source file:Freq.java

public static void main(String[] args) {
    Map<String, Integer> m = new HashMap<String, Integer>();

    // Initialize frequency table from command line
    for (String a : args) {
        Integer freq = m.get(a);/*from www .ja va 2  s  .c  om*/
        m.put(a, (freq == null) ? 1 : freq + 1);
    }

    System.out.println(m.size() + " distinct words:");
    System.out.println(m);
}

From source file:Main.java

public static void main(String[] args) {
    Map<Character, Integer> counting = new HashMap<Character, Integer>();
    String testcase1 = "this is a test";
    for (char ch : testcase1.toCharArray()) {
        Integer freq = counting.get(ch);
        counting.put(ch, (freq == null) ? 1 : freq + 1);
    }//from   ww w  .  j ava 2  s. c om
    System.out.println(counting.size() + " distinct characters:");
    System.out.println(counting);
}

From source file:org.apache.s4.adapter.Adapter.java

public static void main(String args[]) {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c"));

    options.addOption(//from w w  w. ja v a  2s.co  m
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

    options.addOption(
            OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t"));

    options.addOption(OptionBuilder.withArgName("userconfig").hasArg()
            .withDescription("user-defined legacy data adapter configuration file").create("d"));

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }

    int instanceId = -1;
    if (commandLine.hasOption("i")) {
        String instanceIdStr = commandLine.getOptionValue("i");
        try {
            instanceId = Integer.parseInt(instanceIdStr);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad instance id: %s" + instanceIdStr);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("c")) {
        coreHome = commandLine.getOptionValue("c");
    }

    String configType = "typical";
    if (commandLine.hasOption("t")) {
        configType = commandLine.getOptionValue("t");
    }

    String userConfigFilename = null;
    if (commandLine.hasOption("d")) {
        userConfigFilename = commandLine.getOptionValue("d");
    }

    File userConfigFile = new File(userConfigFilename);
    if (!userConfigFile.isFile()) {
        System.err.println("Bad user configuration file: " + userConfigFilename);
        System.exit(1);
    }

    File coreHomeFile = new File(coreHome);
    if (!coreHomeFile.isDirectory()) {
        System.err.println("Bad core home: " + coreHome);
        System.exit(1);
    }

    if (instanceId > -1) {
        System.setProperty("instanceId", "" + instanceId);
    } else {
        System.setProperty("instanceId", "" + S4Util.getPID());
    }

    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = configBase + File.separatorChar + "adapter-conf.xml";
    File configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("adapter config file %s does not exist\n", configPath);
        System.exit(1);
    }

    // load adapter config xml
    ApplicationContext coreContext;
    coreContext = new FileSystemXmlApplicationContext("file:" + configPath);
    ApplicationContext context = coreContext;

    Adapter adapter = (Adapter) context.getBean("adapter");

    ApplicationContext appContext = new FileSystemXmlApplicationContext(
            new String[] { "file:" + userConfigFilename }, context);
    Map listenerBeanMap = appContext.getBeansOfType(EventProducer.class);
    if (listenerBeanMap.size() == 0) {
        System.err.println("No user-defined listener beans");
        System.exit(1);
    }
    EventProducer[] eventListeners = new EventProducer[listenerBeanMap.size()];

    int index = 0;
    for (Iterator it = listenerBeanMap.keySet().iterator(); it.hasNext(); index++) {
        String beanName = (String) it.next();
        System.out.println("Adding producer " + beanName);
        eventListeners[index] = (EventProducer) listenerBeanMap.get(beanName);
    }

    adapter.setEventListeners(eventListeners);
}

From source file:examples.cnn.ImagesClassification.java

public static void main(String[] args) {

    SparkConf conf = new SparkConf();
    conf.setAppName("Images CNN Classification");
    conf.setMaster(String.format("local[%d]", NUM_CORES));
    conf.set(SparkDl4jMultiLayer.AVERAGE_EACH_ITERATION, String.valueOf(true));

    try (JavaSparkContext sc = new JavaSparkContext(conf)) {

        JavaRDD<String> raw = sc.textFile("data/images-data-rgb.csv");
        String first = raw.first();

        JavaPairRDD<String, String> labelData = raw.filter(f -> f.equals(first) == false).mapToPair(r -> {
            String[] tab = r.split(";");
            return new Tuple2<>(tab[0], tab[1]);
        });//from   w w w .jav  a 2s .com

        Map<String, Long> labels = labelData.map(t -> t._1).distinct().zipWithIndex()
                .mapToPair(t -> new Tuple2<>(t._1, t._2)).collectAsMap();

        log.info("Number of labels {}", labels.size());
        labels.forEach((a, b) -> log.info("{}: {}", a, b));

        NetworkTrainer trainer = new NetworkTrainer.Builder().model(ModelLibrary.net1)
                .networkToSparkNetwork(net -> new SparkDl4jMultiLayer(sc, net)).numLabels(labels.size())
                .cores(NUM_CORES).build();

        JavaRDD<Tuple2<INDArray, double[]>> labelsWithData = labelData.map(t -> {
            INDArray label = FeatureUtil.toOutcomeVector(labels.get(t._1).intValue(), labels.size());
            double[] arr = Arrays.stream(t._2.split(" ")).map(normalize1).mapToDouble(Double::doubleValue)
                    .toArray();
            return new Tuple2<>(label, arr);
        });

        JavaRDD<Tuple2<INDArray, double[]>>[] splited = labelsWithData.randomSplit(new double[] { .8, .2 },
                seed);

        JavaRDD<DataSet> testDataset = splited[1].map(t -> {
            INDArray features = Nd4j.create(t._2, new int[] { 1, t._2.length });
            return new DataSet(features, t._1);
        }).cache();
        log.info("Number of test images {}", testDataset.count());

        JavaRDD<DataSet> plain = splited[0].map(t -> {
            INDArray features = Nd4j.create(t._2, new int[] { 1, t._2.length });
            return new DataSet(features, t._1);
        });

        /*
         * JavaRDD<DataSet> flipped = splited[0].randomSplit(new double[] { .5, .5 }, seed)[0].
         */
        JavaRDD<DataSet> flipped = splited[0].map(t -> {
            double[] arr = t._2;
            int idx = 0;
            double[] farr = new double[arr.length];
            for (int i = 0; i < arr.length; i += trainer.width) {
                double[] temp = Arrays.copyOfRange(arr, i, i + trainer.width);
                ArrayUtils.reverse(temp);
                for (int j = 0; j < trainer.height; ++j) {
                    farr[idx++] = temp[j];
                }
            }
            INDArray features = Nd4j.create(farr, new int[] { 1, farr.length });
            return new DataSet(features, t._1);
        });

        JavaRDD<DataSet> trainDataset = plain.union(flipped).cache();
        log.info("Number of train images {}", trainDataset.count());

        trainer.train(trainDataset, testDataset);
    }
}

From source file:com.act.biointerpretation.mechanisminspection.ReactionValidator.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//  w  w w .j av  a 2 s  .  c o m
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(ReactionDesalter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    NoSQLAPI api = new NoSQLAPI(cl.getOptionValue(OPTION_READ_DB), cl.getOptionValue(OPTION_READ_DB));
    MechanisticValidator validator = new MechanisticValidator(api);
    validator.init();

    Map<Integer, List<Ero>> results = validator
            .validateOneReaction(Long.parseLong(cl.getOptionValue(OPTION_RXN_ID)));

    if (results == null) {
        System.out.format("ERROR: validation results are null.\n");
    } else if (results.size() == 0) {
        System.out.format("No matching EROs were found for the specified reaction.\n");
    } else {
        for (Map.Entry<Integer, List<Ero>> entry : results.entrySet()) {
            List<String> eroIds = entry.getValue().stream().map(x -> x.getId().toString())
                    .collect(Collectors.toList());
            System.out.format("%d: %s\n", entry.getKey(), StringUtils.join(eroIds, ", "));
        }
    }
}

From source file:Main.java

public static void main(String args[]) {
    Map<String, Integer> atomNums = new TreeMap<String, Integer>();

    atomNums.put("A", 1);
    atomNums.put("B", 2);
    atomNums.put("C", 3);
    atomNums.put("D", 4);
    atomNums.put("E", 5);
    atomNums.put("F", 6);

    System.out.println("The map contains these " + atomNums.size() + " entries:");

    Set<Map.Entry<String, Integer>> set = atomNums.entrySet();

    for (Map.Entry<String, Integer> me : set) {
        System.out.print(me.getKey() + ", Atomic Number: ");
        System.out.println(me.getValue());
    }//from  w w w. j ava  2 s  .  co m
    TreeMap<String, Integer> atomNums2 = new TreeMap<String, Integer>();

    atomNums2.put("Q", 30);
    atomNums2.put("W", 82);

    atomNums.putAll(atomNums2);

    set = atomNums.entrySet();

    System.out.println("The map now contains these " + atomNums.size() + " entries:");
    for (Map.Entry<String, Integer> me : set) {
        System.out.print(me.getKey() + ", Atomic Number: ");
        System.out.println(me.getValue());
    }

    if (atomNums.containsKey("A"))
        System.out.println("A has an atomic number of " + atomNums.get("A"));

    if (atomNums.containsValue(82))
        System.out.println("The atomic number 82 is in the map.");
    System.out.println();

    if (atomNums.remove("A") != null)
        System.out.println("A has been removed.\n");
    else
        System.out.println("Entry not found.\n");

    Set<String> keys = atomNums.keySet();
    for (String str : keys)
        System.out.println(str + " ");

    Collection<Integer> vals = atomNums.values();
    for (Integer n : vals)
        System.out.println(n + " ");

    atomNums.clear();
    if (atomNums.isEmpty())
        System.out.println("The map is now empty.");
}

From source file:SerialVersionUID.java

/**
 * Generate a mapping of the serial version UIDs for the serializable classes
 * under the jboss dist directory// w  w  w.j av a2  s  . co  m
 * 
 * @param args -
 *          [0] = jboss dist root directory
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.err.println("Usage: jboss-home | -rihome ri-home");
        System.exit(1);
    }
    File distHome = new File(args[0]);
    Map classVersionMap = null;
    if (args.length == 2)
        classVersionMap = generateRISerialVersionUIDReport(distHome);
    else
        classVersionMap = generateJBossSerialVersionUIDReport(distHome);
    // Write the map out the object file
    log.info("Total classes with serialVersionUID != 0: " + classVersionMap.size());
    FileOutputStream fos = new FileOutputStream("serialuid.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(classVersionMap);
    fos.close();
}

From source file:com.act.biointerpretation.ProductExtractor.java

public static void main(String[] args) throws Exception {
    CLIUtil cliUtil = new CLIUtil(ProductExtractor.class, HELP_MESSAGE, OPTION_BUILDERS);
    CommandLine cl = cliUtil.parseCommandLine(args);

    String orgPrefix = cl.getOptionValue(OPTION_ORGANISM_PREFIX);
    LOGGER.info("Using organism prefix %s", orgPrefix);

    MongoDB db = new MongoDB(DEFAULT_DB_HOST, DEFAULT_DB_PORT, cl.getOptionValue(OPTION_DB_NAME));

    Map<Long, String> validOrganisms = new TreeMap<>();
    DBIterator orgIter = db.getDbIteratorOverOrgs();
    Organism o = null;/*from  w  w  w . ja va  2 s  .  c  o m*/
    while ((o = db.getNextOrganism(orgIter)) != null) {
        if (!o.getName().isEmpty() && o.getName().startsWith(orgPrefix)) {
            validOrganisms.put(o.getUUID(), o.getName());
        }
    }

    LOGGER.info("Found %d valid organisms", validOrganisms.size());

    Set<Long> productIds = new TreeSet<>(); // Use something with implicit ordering we can traverse in order.
    DBIterator reactionIterator = db.getIteratorOverReactions();
    Reaction r;
    while ((r = db.getNextReaction(reactionIterator)) != null) {
        Set<JSONObject> proteins = r.getProteinData();
        boolean valid = false;
        for (JSONObject j : proteins) {
            if (j.has("organism") && validOrganisms.containsKey(j.getLong("organism"))) {
                valid = true;
                break;
            } else if (j.has("organisms")) {
                JSONArray organisms = j.getJSONArray("organisms");
                for (int i = 0; i < organisms.length(); i++) {
                    if (validOrganisms.containsKey(organisms.getLong(i))) {
                        valid = true;
                        break;
                    }
                }
            }
        }

        if (valid) {
            for (Long id : r.getProducts()) {
                productIds.add(id);
            }
            for (Long id : r.getProductCofactors()) {
                productIds.add(id);
            }
        }
    }

    LOGGER.info("Found %d valid product ids for '%s'", productIds.size(), orgPrefix);
    PrintWriter writer = cl.hasOption(OPTION_OUTPUT_FILE)
            ? new PrintWriter(new FileWriter(cl.getOptionValue(OPTION_OUTPUT_FILE)))
            : new PrintWriter(System.out);

    for (Long id : productIds) {
        Chemical c = db.getChemicalFromChemicalUUID(id);
        String inchi = c.getInChI();
        if (inchi.startsWith("InChI=") && !inchi.startsWith("InChI=/FAKE")) {
            writer.println(inchi);
        }
    }

    if (cl.hasOption(OPTION_OUTPUT_FILE)) {
        writer.close();
    }
    LOGGER.info("Done.");
}

From source file:org.apache.s4.client.Adapter.java

@SuppressWarnings("static-access")
public static void main(String args[]) throws IOException, InterruptedException {

    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c"));

    options.addOption(/*w  w  w .  ja va 2 s  . c om*/
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

    options.addOption(
            OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t"));

    options.addOption(OptionBuilder.withArgName("userconfig").hasArg()
            .withDescription("user-defined legacy data adapter configuration file").create("d"));

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }

    int instanceId = -1;
    if (commandLine.hasOption("i")) {
        String instanceIdStr = commandLine.getOptionValue("i");
        try {
            instanceId = Integer.parseInt(instanceIdStr);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad instance id: %s" + instanceIdStr);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("c")) {
        coreHome = commandLine.getOptionValue("c");
    }

    String configType = "typical";
    if (commandLine.hasOption("t")) {
        configType = commandLine.getOptionValue("t");
    }

    String userConfigFilename = null;
    if (commandLine.hasOption("d")) {
        userConfigFilename = commandLine.getOptionValue("d");
    }

    File userConfigFile = new File(userConfigFilename);
    if (!userConfigFile.isFile()) {
        System.err.println("Bad user configuration file: " + userConfigFilename);
        System.exit(1);
    }

    File coreHomeFile = new File(coreHome);
    if (!coreHomeFile.isDirectory()) {
        System.err.println("Bad core home: " + coreHome);
        System.exit(1);
    }

    if (instanceId > -1) {
        System.setProperty("instanceId", "" + instanceId);
    } else {
        System.setProperty("instanceId", "" + S4Util.getPID());
    }

    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = configBase + File.separatorChar + "client-adapter-conf.xml";
    File configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("adapter config file %s does not exist\n", configPath);
        System.exit(1);
    }

    // load adapter config xml
    ApplicationContext coreContext;
    coreContext = new FileSystemXmlApplicationContext("file:" + configPath);
    ApplicationContext context = coreContext;

    Adapter adapter = (Adapter) context.getBean("client_adapter");

    ApplicationContext appContext = new FileSystemXmlApplicationContext(
            new String[] { "file:" + userConfigFilename }, context);

    Map<?, ?> inputStubBeanMap = appContext.getBeansOfType(InputStub.class);
    Map<?, ?> outputStubBeanMap = appContext.getBeansOfType(OutputStub.class);

    if (inputStubBeanMap.size() == 0 && outputStubBeanMap.size() == 0) {
        System.err.println("No user-defined input/output stub beans");
        System.exit(1);
    }

    ArrayList<InputStub> inputStubs = new ArrayList<InputStub>(inputStubBeanMap.size());
    ArrayList<OutputStub> outputStubs = new ArrayList<OutputStub>(outputStubBeanMap.size());

    // add all input stubs
    for (Map.Entry<?, ?> e : inputStubBeanMap.entrySet()) {
        String beanName = (String) e.getKey();
        System.out.println("Adding InputStub " + beanName);
        inputStubs.add((InputStub) e.getValue());
    }

    // add all output stubs
    for (Map.Entry<?, ?> e : outputStubBeanMap.entrySet()) {
        String beanName = (String) e.getKey();
        System.out.println("Adding OutputStub " + beanName);
        outputStubs.add((OutputStub) e.getValue());
    }

    adapter.setInputStubs(inputStubs);
    adapter.setOutputStubs(outputStubs);

}

From source file:jmona.driver.Main.java

/**
 * Run the {@link EvolutionContext#stepGeneration()} method until the
 * CompletionConditionon is met, executing any Processors after each
 * generation step.//from w  ww.ja v a  2  s .c o m
 * 
 * Provide the location of the Spring XML configuration file by using the
 * <em>--config</em> command line option, followed by the location of the
 * configuration file. By default, this program will look for a configuration
 * file at <code>./context.xml</code>.
 * 
 * @param args
 *          The command-line arguments to this program.
 */
@SuppressWarnings("unchecked")
public static void main(final String[] args) {
    // set up the list of options which the parser accepts
    setUpParser();

    // get the options from the command line arguments
    final OptionSet options = PARSER.parse(args);

    // get the location of the XML configuration file
    final String configFile = (String) options.valueOf(OPT_CONFIG_FILE);

    // create an application context from the specified XML configuration file
    final ApplicationContext applicationContext = new FileSystemXmlApplicationContext(configFile);

    // get the evolution contexts, completion criteria, and processors
    @SuppressWarnings("rawtypes")
    final Map<String, EvolutionContext> evolutionContextsMap = applicationContext
            .getBeansOfType(EvolutionContext.class);
    @SuppressWarnings("rawtypes")
    final Map<String, CompletionCondition> completionCriteriaMap = applicationContext
            .getBeansOfType(CompletionCondition.class);
    @SuppressWarnings("rawtypes")
    final Map<String, Processor> processorMap = applicationContext.getBeansOfType(Processor.class);

    // assert that there is only one evolution context bean in the app. context
    if (evolutionContextsMap.size() != 1) {
        throw new RuntimeException("Application context contains " + evolutionContextsMap.size()
                + " EvolutionContext beans, but must contain only 1.");
    }

    // assert that there is only one completion criteria bean in the app context
    if (completionCriteriaMap.size() != 1) {
        throw new RuntimeException("Application context contains " + completionCriteriaMap.size()
                + "CompletionCondition beans, but must contain only 1.");
    }

    // get the evolution context and completion condition from their maps
    @SuppressWarnings("rawtypes")
    final EvolutionContext evolutionContext = MapUtils.firstValue(evolutionContextsMap);
    @SuppressWarnings("rawtypes")
    final CompletionCondition completionCondition = MapUtils.firstValue(completionCriteriaMap);

    try {
        // while the criteria has not been satisfied, create the next generation
        while (!completionCondition.execute(evolutionContext)) {
            // create the next generation in the evolution
            evolutionContext.stepGeneration();

            // perform all post-processing on the evolution context
            for (@SuppressWarnings("rawtypes")
            final Processor processor : processorMap.values()) {
                processor.process(evolutionContext);
            }
        }
    } catch (final CompletionException exception) {
        throw new RuntimeException(exception);
    } catch (final EvolutionException exception) {
        throw new RuntimeException(exception);
    } catch (final ProcessingException exception) {
        throw new RuntimeException(exception);
    }
}