Example usage for java.util Map put

List of usage examples for java.util Map put

Introduction

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

Prototype

V put(K key, V value);

Source Link

Document

Associates the specified value with the specified key in this map (optional operation).

Usage

From source file:MapEntrySetDemo.java

public static void main(String[] argv) {

    // Construct and load the hash. This simulates loading a
    // database or reading from a file, or wherever the data is.

    Map map = new HashMap();

    // The hash maps from company name to address.
    // In real life this might map to an Address object...
    map.put("Adobe", "Mountain View, CA");
    map.put("IBM", "White Plains, NY");
    map.put("Learning Tree", "Los Angeles, CA");
    map.put("Microsoft", "Redmond, WA");
    map.put("Netscape", "Mountain View, CA");
    map.put("O'Reilly", "Sebastopol, CA");
    map.put("Sun", "Mountain View, CA");

    // List the entries using entrySet()
    Set entries = map.entrySet();
    Iterator it = entries.iterator();
    while (it.hasNext()) {
        Map.Entry entry = (Map.Entry) it.next();
        System.out.println(entry.getKey() + "-->" + entry.getValue());
    }/* ww w .  j  ava  2s  .c  o  m*/
}

From source file:fr.itinerennes.bundler.integration.onebusaway.GenerateStaticObaApiResults.java

public static void main(String[] args) throws IOException, GtfsException {

    final String url = args[0];
    final String key = args[1];
    final String gtfsFile = args[2];
    final String out = args[3].replaceAll("/$", "");

    final Map<String, String> agencyMapping = new HashMap<String, String>();
    agencyMapping.put("1", "2");
    final GtfsDao gtfs = GtfsUtils.load(new File(gtfsFile), agencyMapping);

    oba = new JsonOneBusAwayClient(new DefaultHttpClient(), url, key);
    gson = OneBusAwayGsonFactory.newInstance(true);

    final Calendar end = Calendar.getInstance();
    end.set(2013, 11, 22, 0, 0);/* w ww.  ja  va2 s.  c  o m*/

    final Calendar start = Calendar.getInstance();
    start.set(2013, 10, 4, 0, 0);

    final Calendar current = Calendar.getInstance();
    current.setTime(start.getTime());

    while (current.before(end) || current.equals(end)) {
        System.out.println(current.getTime());
        for (final Stop stop : gtfs.getAllStops()) {
            final String stopId = stop.getId().toString();
            final String dateDir = String.format("%04d/%02d/%02d", current.get(Calendar.YEAR),
                    current.get(Calendar.MONTH) + 1, current.get(Calendar.DAY_OF_MONTH));
            final String methodDir = String.format("%s/schedule-for-stop", out);

            final File outDir = new File(String.format("%s/%s", methodDir, dateDir));
            outDir.mkdirs();
            final File f = new File(outDir, String.format("%s.json", stopId));

            final StopSchedule ss = oba.getScheduleForStop(stopId, current.getTime());
            final String json = gson.toJson(ss);

            final Writer w = new PrintWriter(f);
            w.write(json);
            w.close();
        }
        current.add(Calendar.DAY_OF_MONTH, 1);
    }

    final File outDir = new File(String.format("%s/trip-details", out));
    outDir.mkdirs();
    for (final Trip trip : gtfs.getAllTrips()) {
        final String tripId = trip.getId().toString();
        final File f = new File(outDir, String.format("%s.json", tripId));

        final TripSchedule ts = oba.getTripDetails(tripId);
        final String json = gson.toJson(ts);

        final Writer w = new PrintWriter(f);
        w.write(json);
        w.close();
    }
}

From source file:Main.java

public static void main(String[] args) {

    String sentence = "is this a sentence this is a test";
    String[] myStringArray = sentence.split("\\s"); // Split the sentence by
                                                    // space.

    Map<String, Integer> wordOccurrences = new HashMap<String, Integer>(myStringArray.length);

    for (String word : myStringArray) {
        if (wordOccurrences.containsKey(word)) {
            wordOccurrences.put(word, wordOccurrences.get(word) + 1);
        } else {//  w  ww  . j av a 2 s . co m
            wordOccurrences.put(word, 1);
        }
    }
    for (String word : wordOccurrences.keySet()) {
        if (wordOccurrences.get(word) > 1) {
            System.out.println("1b. - Tokens that occurs more than once: " + word + "\n");
        }
    }
}

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);/*  www  .  j a  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:com.myjeeva.poi.demo.Excel2JavaDemo.java

/**
 * @param args//  w w w .j  a  va  2s  .c  o  m
 * @throws FileNotFoundException
 */
public static void main(String[] args) throws FileNotFoundException {
    String SAMPLE_PERSON_DATA_FILE_PATH = "src/main/resources/Sample-Person-Data.xlsx";

    // Input File initialize
    File file = new File(SAMPLE_PERSON_DATA_FILE_PATH);
    InputStream inputStream = new FileInputStream(file);

    // Excel Cell Mapping
    Map<String, String> cellMapping = new HashMap<String, String>();
    cellMapping.put("HEADER", "Person Id,Name,Height,Email Address,DOB,Salary");
    cellMapping.put("A", "personId");
    cellMapping.put("B", "name");
    cellMapping.put("C", "height");
    cellMapping.put("D", "emailId");
    cellMapping.put("E", "dob");
    cellMapping.put("F", "salary");

    // The package open is instantaneous, as it should be.
    OPCPackage pkg = null;
    try {

        ExcelWorkSheetHandler<PersonVO> workSheetHandler = new ExcelWorkSheetHandler<PersonVO>(PersonVO.class,
                cellMapping);

        pkg = OPCPackage.open(inputStream);
        ExcelReader excelReader = new ExcelReader(pkg, workSheetHandler);
        excelReader.process();

        if (workSheetHandler.getValueList().isEmpty()) {
            // No data present
            LOG.error("sHandler.getValueList() is empty");
        } else {

            LOG.info(workSheetHandler.getValueList().size()
                    + " no. of records read from given excel worksheet successfully.");

            // Displaying data ead from Excel file
            displayPersonList(workSheetHandler.getValueList());
        }

    } catch (RuntimeException are) {
        LOG.error(are.getMessage(), are.getCause());
    } catch (InvalidFormatException ife) {
        LOG.error(ife.getMessage(), ife.getCause());
    } catch (IOException ioe) {
        LOG.error(ioe.getMessage(), ioe.getCause());
    } finally {
        IOUtils.closeQuietly(inputStream);
        try {
            if (null != pkg) {
                pkg.close();
            }
        } catch (IOException e) {
            // just ignore IO exception
        }
    }
}

From source file:io.kahu.hawaii.util.call.example.Example2.java

public static final void main(String[] args) throws Exception {
    DOMConfigurator.configure(Example2.class.getResource("/log4j.xml").getFile());

    RestServer server = null;/*w  ww . ja va2s . c o m*/
    ExecutorRepository executorRepository = null;
    try {
        /*
         * Create our rest server with a 'ClientResource'.
         */
        server = new RestServer(SERVER_PORT);
        server.addResource(ClientResource.class);
        server.start();

        /*
         * START of generic setup
         */
        // Create a log manager (purpose and explanation out of scope for this example).
        LogManager logManager = new DefaultLogManager(new LogManagerConfiguration(new LoggingConfiguration()));

        // Create an executor, which holds a queue with core size 1, max size 2, a queue of size 2. Threads 'outside the core pool' that are still active after one minute will get cleaned up.
        HawaiiExecutorImpl executor = new HawaiiExecutorImpl(ExecutorRepository.DEFAULT_EXECUTOR_NAME, 1, 2, 2,
                new TimeOut(1, TimeUnit.MINUTES), logManager);
        // Create an executor, which holds a queue with core size 1, max size 2, a queue of size 2. Threads 'outside the core pool' that are still active after one minute will get cleaned up.
        HawaiiExecutorImpl executor2 = new HawaiiExecutorImpl("crm", 1, 2, 2, new TimeOut(1, TimeUnit.MINUTES),
                logManager);

        // Create the repository that holds all executors
        executorRepository = new ExecutorRepository(logManager);
        executorRepository.add(executor);
        executorRepository.add(executor2);

        Map<String, String> defaultExecutors = new HashMap<>();
        defaultExecutors.put("crm", "crm");
        executorRepository.setDefaultExecutors(defaultExecutors);

        // Create a new request dispatcher.
        RequestDispatcher requestDispatcher = new RequestDispatcher(executorRepository, logManager);

        /*
         * END of generic setup
         */

        /*
         * Setup the request (builder).
         */
        HttpRequestContext<Person> context = new HttpRequestContext<>(HttpMethod.GET,
                "http://localhost:" + SERVER_PORT, "/client/{client-id}", "crm", "get_client_by_id",
                new TimeOut(10, TimeUnit.SECONDS));
        CallLogger callLogger = new CallLoggerImpl<>(logManager, new HttpRequestLogger(),
                new JsonPayloadResponseLogger<Person>());
        RequestPrototype<HttpResponse, Person> prototype = new RequestPrototype(requestDispatcher, context,
                new GetCustomerByIdResponseHandler(), callLogger);
        HttpRequestBuilder<Person> getPersonByIdRequest = new HttpRequestBuilder<>(prototype);

        /*
         * Use the request (builder).
         */
        Request<Person> request = getPersonByIdRequest.newInstance().withPathVariables("10").build();
        Person person = request.execute().get();

        System.err.println("CLIENT - Got client '" + person.getName() + "' with id '" + person.getId() + "'.");

    } finally {
        server.stop();
        if (executorRepository != null) {
            executorRepository.stop();
        }
    }

}

From source file:Main.java

public static void main(String args[]) {

    String s = "this is a test this is a test";
    String[] splitted = s.split(" ");
    Map<String, Integer> hm = new HashMap<String, Integer>();

    for (int i = 0; i < splitted.length; i++) {
        if (hm.containsKey(splitted[i])) {
            int cont = hm.get(splitted[i]);
            hm.put(splitted[i], cont + 1);
        } else {//w w  w.  j  a  va  2  s.  c  om
            hm.put(splitted[i], 1);
        }
    }
    System.out.println(hm);
}

From source file:com.clustercontrol.util.StringBinder.java

public static void main(String[] args) {

    String str = "foo #[PARAM] bar #[ESCAPE] #[NOTFOUND] foo";

    Map<String, String> param = new HashMap<String, String>();
    param.put("PARAM", "foofoo");
    byte[] byteCode = { 0x10 };

    param.put("ESCAPE", "foo 'bar' \"foo\" `echo aaa` \\ bar" + " [" + new String(byteCode) + "], ["
            + new String(byteCode) + "]");

    StringBinder binder = new StringBinder(param);
    System.out.println("PARAM : " + param);
    System.out.println("ORIGINAL : " + str);
    System.out.println("BINDED   : " + binder.bindParam(str));
    StringBinder.setReplace(true);/*from w  w  w . j  ava  2  s  . co m*/
    System.out.println("BINDED   : " + binder.bindParam(str));
    StringBinder.setReplaceChar("$");
    StringBinder.setReplace(true);
    System.out.println("BINDED   : " + binder.bindParam(str));
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.MorsaTraverser.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);/*from w w  w  .ja va2s  .  c om*/
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        URI uri = URI.createURI("morsa://" + commandLine.getOptionValue(IN));

        Class<?> inClazz = MorsaTraverser.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put("morsa",
                new MorsaResourceFactoryImpl(new MongoDBMorsaBackendFactory()));

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();
        loadOpts.put(IMorsaResource.OPTION_SERVER_URI, "localhost");
        loadOpts.put(IMorsaResource.OPTION_MAX_SAVE_CACHE_SIZE, 30000);
        loadOpts.put(IMorsaResource.OPTION_DEMAND_LOAD, false);
        //         loadOpts.put(IMorsaResource.OPTION_CACHE_POLICY, FIFOEObjectCachePolicy.class.getName());
        //         loadOpts.put(IMorsaResource.OPTION_MAX_CACHE_SIZE, 30000);
        //         loadOpts.put(IMorsaResource.OPTION_CACHE_FLUSH_FACTOR, 0.3f);
        //         loadOpts.put(IMorsaResource.OPTION_DEMAND_LOAD_STRATEGY, IMorsaResource.OPTION_SINGLE_LOAD_STRATEGY);
        //         loadOpts.put(IMorsaResource.OPTION_DEMAND_LOAD, true);

        resource.load(loadOpts);

        LOG.log(Level.INFO, "Start counting");
        int count = 0;
        long begin = System.currentTimeMillis();
        for (Iterator<EObject> iterator = resource.getAllContents(); iterator.hasNext(); iterator
                .next(), count++)
            ;
        long end = System.currentTimeMillis();
        LOG.log(Level.INFO, "End counting");
        LOG.log(Level.INFO, MessageFormat.format("Resource {0} contains {1} elements", uri, count));
        LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:MainClass.java

public static void main(String[] argv) {
    Map map = new MyMap();

    map.put("Adobe", "Mountain View, CA");
    map.put("Learning Tree", "Los Angeles, CA");
    map.put("IBM", "White Plains, NY");

    String queryString = "Google";
    System.out.println("You asked about " + queryString + ".");
    String resultString = (String) map.get(queryString);
    System.out.println("They are located in: " + resultString);
    System.out.println();//from ww  w  .j  a  v a2  s.  c om

    Iterator k = map.keySet().iterator();
    while (k.hasNext()) {
        String key = (String) k.next();
        System.out.println("Key " + key + "; Value " + (String) map.get(key));
    }

    Set es = map.entrySet();
    System.out.println("entrySet() returns " + es.size() + " Map.Entry's");
}