Example usage for java.util TreeMap get

List of usage examples for java.util TreeMap get

Introduction

In this page you can find the example usage for java.util TreeMap get.

Prototype

public V get(Object key) 

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:Main.java

public static void main(String[] args) {

    TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();

    // populating tree map
    treemap.put(2, "two");
    treemap.put(1, "one");
    treemap.put(3, "three");
    treemap.put(6, "six");
    treemap.put(5, "from java2s.com");

    System.out.println("Checking value for key 3");
    System.out.println("Value is: " + treemap.get(3));
}

From source file:TreeMapDemo.java

public static void main(String args[]) {
    TreeMap<String, Double> tm = new TreeMap<String, Double>();

    tm.put("A", new Double(3.34));
    tm.put("B", new Double(1.22));
    tm.put("C", new Double(1.00));
    tm.put("D", new Double(9.22));
    tm.put("E", new Double(-1.08));

    Set<Map.Entry<String, Double>> set = tm.entrySet();

    for (Map.Entry<String, Double> me : set) {
        System.out.print(me.getKey() + ": ");
        System.out.println(me.getValue());
    }//from   w  ww .  j a v  a 2 s .  c o m

    double balance = tm.get("A");
    tm.put("B", balance + 1000);

    System.out.println(tm.get("A"));
}

From source file:com.github.xbn.examples.io.non_xbn.SizeOrderAllFilesInDirXmpl.java

public static final void main(String[] ignored) {
    File fDir = (new File("R:\\jeffy\\programming\\sandbox\\xbnjava\\xbn\\"));
    Collection<File> cllf = FileUtils.listFiles(fDir, (new String[] { "java" }), true);

    //Add all file paths to a Map, keyed by size.
    //It's actually a map of lists-of-files, to
    //allow multiple files that happen to have the
    //same length.

    TreeMap<Long, List<File>> tmFilesBySize = new TreeMap<Long, List<File>>();
    Iterator<File> itrf = cllf.iterator();
    while (itrf.hasNext()) {
        File f = itrf.next();//from w w w .  ja v a2  s. c o  m
        Long LLen = f.length();
        if (!tmFilesBySize.containsKey(LLen)) {
            ArrayList<File> alf = new ArrayList<File>();
            alf.add(f);
            tmFilesBySize.put(LLen, alf);
        } else {
            tmFilesBySize.get(LLen).add(f);
        }
    }

    //Iterate backwards by key through the map. For each
    //List<File>, iterate through the files, printing out
    //its size and path.

    ArrayList<Long> alSize = new ArrayList<Long>(tmFilesBySize.keySet());
    for (int i = alSize.size() - 1; i >= 0; i--) {
        itrf = tmFilesBySize.get(alSize.get(i)).iterator();
        while (itrf.hasNext()) {
            File f = itrf.next();
            System.out.println(f.length() + ": " + f.getPath());
        }
    }
}

From source file:module.entities.UsernameChecker.CheckOpengovUsernames.java

/**
 * @param args the command line arguments
 *//*w w  w .ja  va  2s  .  c om*/
public static void main(String[] args) throws SQLException, IOException {
    //        args = new String[1];
    //        args[0] = "searchConf.txt";
    Date d = new Date();
    long milTime = d.getTime();
    long execStart = System.nanoTime();
    Timestamp startTime = new Timestamp(milTime);
    long lStartTime;
    long lEndTime = 0;
    int status_id = 1;
    JSONObject obj = new JSONObject();
    if (args.length != 1) {
        System.out.println("None or too many argument parameters where defined! "
                + "\nPlease provide ONLY the configuration file name as the only argument.");
    } else {
        try {
            configFile = args[0];
            initLexicons();
            Database.init();
            lStartTime = System.currentTimeMillis();
            System.out.println("Opengov username identification process started at: " + startTime);
            usernameCheckerId = Database.LogUsernameChecker(lStartTime);
            TreeMap<Integer, String> OpenGovUsernames = Database.GetOpenGovUsers();
            HashSet<ReportEntry> report_names = new HashSet<>();
            if (OpenGovUsernames.size() > 0) {
                for (int userID : OpenGovUsernames.keySet()) {
                    String DBusername = Normalizer
                            .normalize(OpenGovUsernames.get(userID).toUpperCase(locale), Normalizer.Form.NFD)
                            .replaceAll("\\p{M}", "");
                    String username = "";
                    int type;
                    String[] splitUsername = DBusername.split(" ");
                    if (checkNameInLexicons(splitUsername)) {
                        for (String splText : splitUsername) {
                            username += splText + " ";
                        }
                        type = 1;
                    } else if (checkOrgInLexicons(splitUsername)) {
                        for (String splText : splitUsername) {
                            username += splText + " ";
                        }
                        type = 2;
                    } else {
                        username = DBusername;
                        type = -1;
                    }
                    ReportEntry cerEntry = new ReportEntry(userID, username.trim(), type);
                    report_names.add(cerEntry);
                }
                status_id = 2;
                obj.put("message", "Opengov username checker finished with no errors");
                obj.put("details", "");
                Database.UpdateOpengovUsersReportName(report_names);
                lEndTime = System.currentTimeMillis();
            } else {
                status_id = 2;
                obj.put("message", "Opengov username checker finished with no errors");
                obj.put("details", "No usernames needed to be checked");
                lEndTime = System.currentTimeMillis();
            }
        } catch (Exception ex) {
            System.err.println(ex.getMessage());
            status_id = 3;
            obj.put("message", "Opengov username checker encountered an error");
            obj.put("details", ex.getMessage().toString());
            lEndTime = System.currentTimeMillis();
        }
    }
    long execEnd = System.nanoTime();
    long executionTime = (execEnd - execStart);
    System.out.println("Total process time: " + (((executionTime / 1000000) / 1000) / 60) + " minutes.");
    Database.UpdateLogUsernameChecker(lEndTime, status_id, usernameCheckerId, obj);
    Database.closeConnection();
}

From source file:MainClass.java

public static void main(String args[]) {

    TreeMap<String, Double> tm = new TreeMap<String, Double>();

    tm.put("A", new Double(3434.34));
    tm.put("B", new Double(123.22));
    tm.put("C", new Double(1378.00));
    tm.put("D", new Double(99.22));
    tm.put("E", new Double(-19.08));

    Set<Map.Entry<String, Double>> set = tm.entrySet();

    for (Map.Entry<String, Double> me : set) {
        System.out.print(me.getKey() + ": ");
        System.out.println(me.getValue());
    }/*from   w ww  .j av  a  2s  .  c o  m*/
    System.out.println();

    double balance = tm.get("B");
    tm.put("B", balance + 1000);

    System.out.println("B's new balance: " + tm.get("B"));
}

From source file:com.kaikoda.cah.CardGenerator.java

/**
 * Generates a printable deck of Cards Against Humanity.
 * //from  w  w w.  jav  a  2s .c o  m
 * @param args where to find the data file and optionally the dictionary and
 *        target language if translation is required.
 * @throws CardGeneratorConfigurationException when it's not possible to
 *         construct a usable instance of CardGenerator.
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws ParseException if there are any problems encountered while
 *         parsing the command line tokens.
 */
public static void main(String[] args) throws CardGeneratorConfigurationException, ParseException, SAXException,
        IOException, ParserConfigurationException {

    ProgressReporterMode verbosity = ProgressReporterMode.NORMAL;

    CardGenerator generator = new CardGenerator();
    generator.setVerbosity(verbosity);

    // Configure valid options accepted from the command-line
    CardGeneratorOptions options = new CardGeneratorOptions();

    // Interpret the arguments supplied at runtime.
    TreeMap<String, String> params = options.parse(args);

    // Check whether a level of verbosity has been specified.
    if (params.containsKey("verbosity")) {
        verbosity = ProgressReporterMode.valueOf(params.get("verbosity").toUpperCase());
        generator.setVerbosity(verbosity);
    }

    // Check whether help has been requested.
    if (params.containsKey("help")) {

        if (verbosity.equals(ProgressReporterMode.NORMAL)) {

            // Print a list of the options that can be used with
            // CardGenerator.
            System.out.println("\n" + params.get("help"));

        }

    } else {

        File data = new File(params.remove("path-to-data"));

        CardGeneratorProduct product = CardGeneratorProduct.HTML;
        if (params.containsKey("product")) {
            product = CardGeneratorProduct.valueOf(params.remove("product").toUpperCase());
        }

        Locale targetLanguage = null;
        if (params.containsKey("output-language")) {
            targetLanguage = Locale.forLanguageTag(params.remove("output-language"));
        }

        File dictionary = null;
        if (params.containsKey("path-to-dictionary")) {
            dictionary = new File(params.remove("path-to-dictionary"));
        }

        generator.generate(data, targetLanguage, dictionary, product);

    }
}

From source file:TComp.java

public static void main(String args[]) {
    TreeMap<String, Double> tm = new TreeMap<String, Double>(new TComp());

    tm.put("J D", new Double(3434.34));
    tm.put("T S", new Double(123.22));
    tm.put("J B", new Double(1378.00));
    tm.put("T H", new Double(99.22));
    tm.put("R S", new Double(-19.08));

    Set<Map.Entry<String, Double>> set = tm.entrySet();

    for (Map.Entry<String, Double> me : set) {
        System.out.print(me.getKey() + ": ");
        System.out.println(me.getValue());
    }//from  www.j a  v  a  2 s  . c o m
    System.out.println();

    double balance = tm.get("A");
    tm.put("A", balance + 1000);

    System.out.println("A's new balance: " + tm.get("A"));
}

From source file:module.entities.NameFinder.RegexNameFinder.java

/**
 * @param args the command line arguments
 *///  w  w w .j a v a  2s.c  o  m
public static void main(String[] args) throws SQLException, IOException {

    if (args.length == 1) {
        Config.configFile = args[0];
    }
    long lStartTime = System.currentTimeMillis();
    Timestamp startTime = new Timestamp(lStartTime);
    System.out.println("Regex Name Finder process started at: " + startTime);
    DB.initPostgres();
    regexerId = DB.LogRegexFinder(lStartTime);
    initLexicons();
    JSONObject obj = new JSONObject();
    TreeMap<Integer, String> consultations = DB.getDemocracitConsultationBody();
    Document doc;
    int count = 0;
    TreeMap<Integer, String> consFoundNames = new TreeMap<>();
    TreeMap<Integer, String> consFoundRoles = new TreeMap<>();
    for (int consId : consultations.keySet()) {
        String consBody = consultations.get(consId);
        String signName = "", roleName = "";
        doc = Jsoup.parse(consBody);
        Elements allPars = new Elements();
        Elements paragraphs = doc.select("p");
        for (Element par : paragraphs) {
            if (par.html().contains("<br>")) {
                String out = "<p>" + par.html().replaceAll("<br>", "</p><p>") + "</p>";
                Document internal_doc = Jsoup.parse(out);
                Elements subparagraphs = internal_doc.select("p");
                allPars.addAll(subparagraphs);
            } else {
                allPars.add(par);
            }
            //                System.out.println(formatedText);
        }
        String signature = getSignatureFromParagraphs(allPars);
        //            System.out.println(signature);
        if (signature.contains("#")) {
            String[] sign_tokens = signature.split("#");
            signName = sign_tokens[0];
            if (sign_tokens.length > 1) {
                roleName = sign_tokens[1];
            }
            consFoundNames.put(consId, signName.trim());
            consFoundRoles.put(consId, roleName.trim());
            count++;
        } else {
            System.err.println("--" + consId);
        }
        //           
    }
    DB.insertDemocracitConsultationMinister(consFoundNames, consFoundRoles);

    TreeMap<Integer, String> consultationsCompletedText = DB.getDemocracitCompletedConsultationBody();
    Document doc2;
    TreeMap<Integer, String> complConsFoundNames = new TreeMap<>();
    int count2 = 0;
    for (int consId : consultationsCompletedText.keySet()) {
        String consBody = consultationsCompletedText.get(consId);
        String signName = "", roleName = "";
        doc2 = Jsoup.parse(consBody);
        //            if (doc.text().contains("<br>")) {
        //                doc.text().replaceAll("(<[Bb][Rr]>)+", "<p>");
        //            }
        Elements allPars = new Elements();
        Elements paragraphs = doc2.select("p");
        for (Element par : paragraphs) {

            if (par.html().contains("<br>")) {
                String out = "<p>" + par.html().replaceAll("<br>", "</p><p>") + "</p>";
                Document internal_doc = Jsoup.parse(out);
                Elements subparagraphs = internal_doc.select("p");
                allPars.addAll(subparagraphs);
            } else {
                allPars.add(par);
            }
        }
        String signature = getSignatureFromParagraphs(allPars);
        if (signature.contains("#")) {
            String[] sign_tokens = signature.split("#");
            signName = sign_tokens[0];
            if (sign_tokens.length > 1) {
                roleName = sign_tokens[1];
            }
            consFoundNames.put(consId, signName.trim());
            consFoundRoles.put(consId, roleName.trim());
            //                System.out.println(consId);
            //                System.out.println(signName.trim());
            //                System.out.println("***************");
            count2++;
        } else {
            System.err.println("++" + consId);
        }
    }
    DB.insertDemocracitConsultationMinister(complConsFoundNames, consFoundRoles);
    long lEndTime = System.currentTimeMillis();
    System.out.println("Regex Name Finder process finished at: " + startTime);
    obj.put("message", "Regex Name Finder finished with no errors");
    obj.put("details", "");
    DB.UpdateLogRegexFinder(lEndTime, regexerId, obj);
    DB.close();
}

From source file:cosmos.example.BuildingPermitsExample.java

public static void main(String[] args) throws Exception {
    BuildingPermitsExample example = new BuildingPermitsExample();
    new JCommander(example, args);

    File inputFile = new File(example.fileName);

    Preconditions.checkArgument(inputFile.exists() && inputFile.isFile() && inputFile.canRead(),
            "Expected " + example.fileName + " to be a readable file");

    String zookeepers;/* w ww.j  a v a 2 s .com*/
    String instanceName;
    Connector connector;
    MiniAccumuloCluster mac = null;
    File macDir = null;

    // Use the MiniAccumuloCluster is requested
    if (example.useMiniAccumuloCluster) {
        macDir = Files.createTempDir();
        String password = "password";
        MiniAccumuloConfig config = new MiniAccumuloConfig(macDir, password);
        config.setNumTservers(1);

        mac = new MiniAccumuloCluster(config);
        mac.start();

        zookeepers = mac.getZooKeepers();
        instanceName = mac.getInstanceName();

        ZooKeeperInstance instance = new ZooKeeperInstance(instanceName, zookeepers);
        connector = instance.getConnector("root", new PasswordToken(password));
    } else {
        // Otherwise connect to a running instance
        zookeepers = example.zookeepers;
        instanceName = example.instanceName;

        ZooKeeperInstance instance = new ZooKeeperInstance(instanceName, zookeepers);
        connector = instance.getConnector(example.username, new PasswordToken(example.password));
    }

    // Instantiate an instance of Cosmos
    Cosmos cosmos = new CosmosImpl(zookeepers);

    // Create a definition for the data we want to load
    Store id = Store.create(connector, new Authorizations(), AscendingIndexIdentitySet.create());

    // Register the definition with Cosmos so it can track its progress.
    cosmos.register(id);

    // Load all of the data from our inputFile
    LoadBuildingPermits loader = new LoadBuildingPermits(cosmos, id, inputFile);
    loader.run();

    // Finalize the SortableResult which will prevent future writes to the data set
    cosmos.finalize(id);

    // Flush the ingest traces to the backend so we can see the results;
    id.sendTraces();

    // Get back the Set of Columns that we've ingested.
    Set<Column> schema = Sets.newHashSet(cosmos.columns(id));

    log.debug("\nColumns: " + schema);

    Iterator<Column> iter = schema.iterator();
    while (iter.hasNext()) {
        Column c = iter.next();
        // Remove the internal ID field and columns that begin with CONTRACTOR_
        if (c.equals(LoadBuildingPermits.ID) || c.name().startsWith("CONTRACTOR_")) {
            iter.remove();
        }
    }

    Iterable<Index> indices = Iterables.transform(schema, new Function<Column, Index>() {

        @Override
        public Index apply(Column col) {
            return Index.define(col);
        }

    });

    // Ensure that we have locality groups set as we expect
    log.info("Ensure locality groups are set");
    id.optimizeIndices(indices);

    // Compact down the data for this SortableResult    
    log.info("Issuing compaction for relevant data");
    id.consolidate();

    final int numTopValues = 10;

    // Walk through each column in the result set
    for (Column c : schema) {
        Stopwatch sw = new Stopwatch();
        sw.start();

        // Get the number of times we've seen each value in a given column
        CloseableIterable<Entry<RecordValue<?>, Long>> groupingsInColumn = cosmos.groupResults(id, c);

        log.info(c.name() + ":");

        // Iterate over the counts, collecting the top N values in each column
        TreeMap<Long, RecordValue<?>> topValues = Maps.newTreeMap();

        for (Entry<RecordValue<?>, Long> entry : groupingsInColumn) {
            if (topValues.size() == numTopValues) {
                Entry<Long, RecordValue<?>> least = topValues.pollFirstEntry();

                if (least.getKey() < entry.getValue()) {
                    topValues.put(entry.getValue(), entry.getKey());
                } else {
                    topValues.put(least.getKey(), least.getValue());
                }
            } else if (topValues.size() < numTopValues) {
                topValues.put(entry.getValue(), entry.getKey());
            }
        }

        for (Long key : topValues.descendingKeySet()) {
            log.info(topValues.get(key).value() + " occurred " + key + " times");
        }

        sw.stop();

        log.info("Took " + sw.toString() + " to run query.\n");
    }

    log.info("Deleting records");

    // Delete the records we've ingested
    if (!example.useMiniAccumuloCluster) {
        // Because I'm lazy and don't want to wait around to run the BatchDeleter when we're just going
        // to rm -rf the directory in a few secs.
        cosmos.delete(id);
    }

    // And shut down Cosmos
    cosmos.close();

    log.info("Cosmos stopped");

    // If we were using MAC, also stop that
    if (example.useMiniAccumuloCluster && null != mac) {
        mac.stop();
        if (null != macDir) {
            FileUtils.deleteDirectory(macDir);
        }
    }
}

From source file:cht.Parser.java

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

    // TODO get from google drive
    boolean isUnicode = false;
    boolean isRemoveInputFileOnComplete = false;
    int rowNum;//from  w w w  . j av  a  2  s. c om
    int colNum;
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    Properties prop = new Properties();

    try {
        prop.load(new FileInputStream("config.txt"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    String inputFilePath = prop.getProperty("inputFile");
    String outputDirectory = prop.getProperty("outputDirectory");
    System.out.println(outputDirectory);
    // optional
    String unicode = prop.getProperty("unicode");
    String removeInputFileOnComplete = prop.getProperty("removeInputFileOnComplete");

    inputFilePath = inputFilePath.trim();
    outputDirectory = outputDirectory.trim();

    if (unicode != null) {
        isUnicode = Boolean.parseBoolean(unicode.trim());
    }
    if (removeInputFileOnComplete != null) {
        isRemoveInputFileOnComplete = Boolean.parseBoolean(removeInputFileOnComplete.trim());
    }

    Writer out = null;
    FileInputStream in = null;
    final String newLine = System.getProperty("line.separator").toString();
    final String separator = File.separator;
    try {
        in = new FileInputStream(inputFilePath);

        Workbook workbook = new XSSFWorkbook(in);

        Sheet sheet = workbook.getSheetAt(0);

        rowNum = sheet.getLastRowNum() + 1;
        colNum = sheet.getRow(0).getPhysicalNumberOfCells();

        for (int j = 1; j < colNum; ++j) {
            String outputFilename = sheet.getRow(0).getCell(j).getStringCellValue();
            // guess directory
            int slash = outputFilename.indexOf('/');
            if (slash != -1) { // has directory
                outputFilename = outputFilename.substring(0, slash) + separator
                        + outputFilename.substring(slash + 1);
            }

            String outputPath = FilenameUtils.concat(outputDirectory, outputFilename);
            System.out.println("--Writing " + outputPath);
            out = new OutputStreamWriter(new FileOutputStream(outputPath), "UTF-8");
            TreeMap<String, Object> map = new TreeMap<String, Object>();
            for (int i = 1; i < rowNum; i++) {
                try {
                    String key = sheet.getRow(i).getCell(0).getStringCellValue();
                    //String value = "";
                    Cell tmp = sheet.getRow(i).getCell(j);
                    if (tmp != null) {
                        // not empty string!
                        value = sheet.getRow(i).getCell(j).getStringCellValue();
                    }
                    if (!key.equals("") && !key.startsWith("#") && !key.startsWith(".")) {
                        value = isUnicode ? StringEscapeUtils.escapeJava(value) : value;

                        int firstdot = key.indexOf(".");
                        String keyName, keyAttribute;
                        if (firstdot > 0) {// a.b.c.d 
                            keyName = key.substring(0, firstdot); // a
                            keyAttribute = key.substring(firstdot + 1); // b.c.d
                            TreeMap oldhash = null;
                            Object old = null;
                            if (map.get(keyName) != null) {
                                old = map.get(keyName);
                                if (old instanceof TreeMap == false) {
                                    System.out.println("different type of key:" + key);
                                    continue;
                                }
                                oldhash = (TreeMap) old;
                            } else {
                                oldhash = new TreeMap();
                            }

                            int firstdot2 = keyAttribute.indexOf(".");
                            String rootName, childName;
                            if (firstdot2 > 0) {// c, d.f --> d, f
                                rootName = keyAttribute.substring(0, firstdot2);
                                childName = keyAttribute.substring(firstdot2 + 1);
                            } else {// c, d  -> d, null
                                rootName = keyAttribute;
                                childName = null;
                            }

                            TreeMap<String, Object> object = myPut(oldhash, rootName, childName);
                            map.put(keyName, object);

                        } else {// c, d  -> d, null
                            keyName = key;
                            keyAttribute = null;
                            // simple string mode
                            map.put(key, value);
                        }

                    }

                } catch (Exception e) {
                    // just ingore empty rows
                }

            }
            String json = gson.toJson(map);
            // output json
            out.write(json + newLine);
            out.close();
        }
        in.close();

        System.out.println("\n---Complete!---");
        System.out.println("Read input file from " + inputFilePath);
        System.out.println(colNum - 1 + " output files ate generated at " + outputDirectory);
        System.out.println(rowNum + " records are generated for each output file.");
        System.out.println("output file is ecoded as unicode? " + (isUnicode ? "yes" : "no"));
        if (isRemoveInputFileOnComplete) {
            File input = new File(inputFilePath);
            input.deleteOnExit();
            System.out.println("Deleted " + inputFilePath);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            in.close();
        }
    }

}