Example usage for java.util Map keySet

List of usage examples for java.util Map keySet

Introduction

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

Prototype

Set<K> keySet();

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:ArrayMap.java

public static void main(String args[]) {
    Map map = new ArrayMap(13);
    map.put("1", "One");
    map.put("2", "Two");
    map.put("3", "Three");
    map.put("4", "Four");
    map.put("5", "Five");
    map.put("6", "Six");
    map.put("7", "Seven");
    map.put("8", "Eight");
    map.put("9", "Nine");
    map.put("10", "Ten");
    map.put("11", "Eleven");
    map.put("12", "Twelve");
    map.put("13", "Thirteen");
    System.out.println(map);//from  ww  w  . java 2s  .  c  o  m
    System.out.println(map.keySet());
    System.out.println(map.values());
}

From source file:TweetAttributes.java

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

    int k = Integer.parseInt(args[0]);
    String inputFile = args[1];/* w w  w . ja v a 2  s  .  com*/
    String initialSeedsFile = args[2];
    String outputFile = args[3];

    KMeansJaccard kmj = new KMeansJaccard(k);
    kmj.makeTweetObjects(inputFile);
    List<TweetAttributes> centroidPoints = kmj.getInitialCentroids(initialSeedsFile);

    Map<Long, List<Double>> distanceMap = new LinkedHashMap<>();
    List<TweetAttributes> tweets = kmj.getTweetList();

    buildDistanceMap(centroidPoints, tweets, kmj, distanceMap);

    for (Long i : distanceMap.keySet()) {
        kmj.assignClusterToTweet(i, distanceMap.get(i));
    }

    List<TweetAttributes> tweetCopy = tweets;
    List<TweetAttributes> centroidCopy = centroidPoints;

    double cost = calculateCost(tweets, centroidPoints, kmj);

    Map<Integer, List<TweetAttributes>> tweetClusterMapping = getTweetCLusterMapping(tweets);

    for (Integer i : tweetClusterMapping.keySet()) {
        List<TweetAttributes> ta = tweetClusterMapping.get(i);
        for (TweetAttributes tweet : ta) {
            centroidPoints.remove(i - 1);
            centroidPoints.add(i - 1, tweet);

            distanceMap.clear();
            buildDistanceMap(centroidPoints, tweets, kmj, distanceMap);

            for (Long id : distanceMap.keySet()) {
                kmj.assignClusterToTweet(id, distanceMap.get(id));
            }

            double newCost = calculateCost(tweets, centroidPoints, kmj);

            if (newCost < cost) {
                cost = newCost;
                tweetCopy = kmj.getTweetList();
                centroidCopy = kmj.getCentroidList();
            }

        }
    }
    double sse = calculateSSE(tweetCopy, centroidCopy, kmj);
    System.out.println("COST: " + cost + " " + "SSE:" + sse);
    writeOutputToFile(tweetCopy, outputFile);

}

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();//w  w  w  .ja v  a  2 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");
}

From source file:edu.cuhk.hccl.evaluation.EvaluationApp.java

public static void main(String[] args) throws IOException, TasteException {
    File realFile = new File(args[0]);
    File estimateFile = new File(args[1]);

    // Build real-rating map
    Map<String, long[]> realMap = buildRatingMap(realFile);

    // Build estimate-rating map
    Map<String, long[]> estimateMap = buildRatingMap(estimateFile);

    // Compare realMap with estimateMap
    Map<Integer, List<Double>> realList = new HashMap<Integer, List<Double>>();
    Map<Integer, List<Double>> estimateList = new HashMap<Integer, List<Double>>();

    // Use set to store non-duplicate pairs only
    Set<String> noRatingList = new HashSet<String>();

    for (String pair : realMap.keySet()) {
        long[] realRatings = realMap.get(pair);
        long[] estimateRatings = estimateMap.get(pair);

        if (realRatings == null || estimateRatings == null)
            continue;

        for (int i = 0; i < realRatings.length; i++) {
            long real = realRatings[i];
            long estimate = estimateRatings[i];

            // continue if the aspect rating can not be estimated due to incomplete reviews
            if (estimate <= 0) {
                noRatingList.add(pair.replace("@", "\t"));
                continue;
            }/*from   w w w.  ja v a  2 s.  co m*/

            if (real > 0 && estimate > 0) {
                if (!realList.containsKey(i))
                    realList.put(i, new ArrayList<Double>());

                realList.get(i).add((double) real);

                if (!estimateList.containsKey(i))
                    estimateList.put(i, new ArrayList<Double>());

                estimateList.get(i).add((double) estimate);
            }
        }
    }

    System.out.println("[INFO] RMSE, MAE for estimate ratings: ");
    System.out.println("------------------------------");
    System.out.println("Index \t RMSE \t MAE");
    for (int i = 1; i < 6; i++) {
        double rmse = Metric.computeRMSE(realList.get(i), estimateList.get(i));
        double mae = Metric.computeMAE(realList.get(i), estimateList.get(i));

        System.out.printf("%d \t %.3f \t %.3f \n", i, rmse, mae);
    }

    System.out.println("------------------------------");

    if (noRatingList.size() > 0) {
        String noRatingFileName = "evaluation-no-ratings.txt";
        FileUtils.writeLines(new File(noRatingFileName), noRatingList, false);

        System.out.println("[INFO] User-item pairs with no ratings are saved in file: " + noRatingFileName);
    } else {
        System.out.println("[INFO] All user-item pairs have ratings.");
    }
}

From source file:TreeMapExample.java

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

    // Add Items to the TreeMap
    map.put(new Integer(1), "One");
    map.put(new Integer(2), "Two");
    map.put(new Integer(3), "Three");
    map.put(new Integer(4), "Four");
    map.put(new Integer(5), "Five");
    map.put(new Integer(6), "Six");
    map.put(new Integer(7), "Seven");
    map.put(new Integer(8), "Eight");
    map.put(new Integer(9), "Nine");
    map.put(new Integer(10), "Ten");

    // Use iterator to display the keys and associated values
    System.out.println("Map Values Before: ");
    Set keys = map.keySet();
    for (Iterator i = keys.iterator(); i.hasNext();) {
        Integer key = (Integer) i.next();
        String value = (String) map.get(key);
        System.out.println(key + " = " + value);
    }/*  w ww.ja va  2s .  com*/

    // Remove the entry with key 6
    System.out.println("\nRemove element with key 6");
    map.remove(new Integer(6));

    // Use iterator to display the keys and associated values
    System.out.println("\nMap Values After: ");
    keys = map.keySet();
    for (Iterator i = keys.iterator(); i.hasNext();) {
        Integer key = (Integer) i.next();
        String value = (String) map.get(key);
        System.out.println(key + " = " + value);
    }
}

From source file:org.test.LookupSVNUsers.java

/**
 * @param args//w  w w .  ja  v a 2  s  .c o  m
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {

    if (args.length != 2) {
        log.error("USAGE: <svn users file(input)> <git authors file (output)>");

        System.exit(-1);
    }

    Set<String> unmatchedNameSet = new LinkedHashSet<String>();

    Map<String, GitUser> gitUserMap = new LinkedHashMap<String, GitUser>();

    String svnAuthorsFile = args[0];

    List<String> lines = FileUtils.readLines(new File(svnAuthorsFile));

    for (String line : lines) {

        // intentionally handle both upper and lower case varients of the same name.
        String svnUserName = line.trim();

        if (svnUserName.contains("("))
            continue; // skip over this line as we can't use it on the url

        if (gitUserMap.keySet().contains(svnUserName))
            continue; // skip this duplicate.

        log.info("starting on user = " + svnUserName);

        String gitName = extractFullName(svnUserName);

        if (gitName == null) {

            gitName = extractFullName(svnUserName.toLowerCase());
        }

        if (gitName == null) {
            unmatchedNameSet.add(svnUserName);
        } else {

            gitUserMap.put(svnUserName, new GitUser(svnUserName, gitName));
            log.info("mapped user (" + svnUserName + ") to: " + gitName);

        }

    }

    List<String> mergedList = new ArrayList<String>();

    mergedList.add("# GENERATED ");

    List<String> userNameList = new ArrayList<String>();

    userNameList.addAll(gitUserMap.keySet());

    Collections.sort(userNameList);

    for (String userName : userNameList) {

        GitUser gUser = gitUserMap.get(userName);

        mergedList.add(gUser.getSvnAuthor() + " = " + gUser.getGitUser() + " <" + gUser.getSvnAuthor()
                + "@users.sourceforge.net>");

    }

    for (String username : unmatchedNameSet) {

        log.warn("failed to match SVN User = " + username);

        // add in the unmatched entries as is.
        mergedList.add(username + " = " + username + " <" + username + "@users.sourceforge.net>");
    }

    FileUtils.writeLines(new File(args[1]), "UTF-8", mergedList);

}

From source file:mvm.rya.indexing.external.ExternalIndexMain.java

public static void main(String[] args) throws Exception {
    Preconditions.checkArgument(args.length == 6, "java " + ExternalIndexMain.class.getCanonicalName()
            + " sparqlFile cbinstance cbzk cbuser cbpassword rdfTablePrefix.");

    final String sparqlFile = args[0];

    instStr = args[1];//  w w  w  .  ja  va  2s  .  c  o m
    zooStr = args[2];
    userStr = args[3];
    passStr = args[4];
    tablePrefix = args[5];

    String queryString = FileUtils.readFileToString(new File(sparqlFile));

    // Look for Extra Indexes
    Instance inst = new ZooKeeperInstance(instStr, zooStr);
    Connector c = inst.getConnector(userStr, passStr.getBytes());

    System.out.println("Searching for Indexes");
    Map<String, String> indexTables = Maps.newLinkedHashMap();
    for (String table : c.tableOperations().list()) {
        if (table.startsWith(tablePrefix + "INDEX_")) {
            Scanner s = c.createScanner(table, new Authorizations());
            s.setRange(Range.exact(new Text("~SPARQL")));
            for (Entry<Key, Value> e : s) {
                indexTables.put(table, e.getValue().toString());
            }
        }
    }

    List<ExternalTupleSet> index = Lists.newArrayList();

    if (indexTables.isEmpty()) {
        System.out.println("No Index found");
    } else {
        for (String table : indexTables.keySet()) {
            String indexSparqlString = indexTables.get(table);
            System.out.println("====================== INDEX FOUND ======================");
            System.out.println(" table : " + table);
            System.out.println(" sparql : ");
            System.out.println(indexSparqlString);

            index.add(new AccumuloIndexSet(indexSparqlString, c, table));
        }
    }

    // Connect to Rya
    Sail s = getRyaSail();
    SailRepository repo = new SailRepository(s);
    repo.initialize();

    // Perform Query

    CountingTupleQueryResultHandler count = new CountingTupleQueryResultHandler();

    SailRepositoryConnection conn;
    if (index.isEmpty()) {
        conn = repo.getConnection();

    } else {
        ExternalProcessor processor = new ExternalProcessor(index);

        Sail processingSail = new ExternalSail(s, processor);
        SailRepository smartSailRepo = new SailRepository(processingSail);
        smartSailRepo.initialize();

        conn = smartSailRepo.getConnection();
    }

    startTime = System.currentTimeMillis();
    lastTime = startTime;
    System.out.println("Query Started");
    conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString).evaluate(count);

    System.out.println("Count of Results found : " + count.i);
    System.out.println("Total query time (s) : " + (System.currentTimeMillis() - startTime) / 1000.);
}

From source file:hk.idv.kenson.jrconsole.Console.java

/**
 * @param args/*from  w w  w .ja  va  2 s  . c  o  m*/
 */
public static void main(String[] args) {
    try {
        Map<String, Object> params = Console.parseArgs(args);
        if (params.containsKey("help")) {
            printUsage();
            return;
        }
        if (params.containsKey("version")) {
            System.err.println("Version: " + VERSION);
            return;
        }
        if (params.containsKey("debug")) {
            for (String key : params.keySet())
                log.info("\"" + key + "\" => \"" + params.get(key) + "\"");
            return;
        }

        checkParam(params);
        stepCompile(params);
        JasperReport jasper = stepLoadReport(params);
        JasperPrint print = stepFill(jasper, params);
        InputStream stream = stepExport(print, params);

        File output = new File(params.get("output").toString());
        FileOutputStream fos = new FileOutputStream(output);
        copy(stream, fos);

        fos.close();
        stream.close();
        System.out.println(output.getAbsolutePath()); //Output the report path for pipe
    } catch (IllegalArgumentException ex) {
        printUsage();
        System.err.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } catch (RuntimeException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new RuntimeException("Unexpected exception", ex);
    }
}

From source file:com.buddycloud.channeldirectory.cli.Main.java

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

    JsonElement rootElement = new JsonParser().parse(new FileReader(QUERIES_FILE));
    JsonArray rootArray = rootElement.getAsJsonArray();

    Map<String, Query> queries = new HashMap<String, Query>();

    for (int i = 0; i < rootArray.size(); i++) {
        JsonObject queryElement = rootArray.get(i).getAsJsonObject();
        String queryName = queryElement.get("name").getAsString();
        String type = queryElement.get("type").getAsString();

        Query query = null;/*from  www .  j av  a  2 s.  c o m*/

        if (type.equals("solr")) {
            query = new QueryToSolr(queryElement.get("agg").getAsString(),
                    queryElement.get("core").getAsString(), queryElement.get("q").getAsString());
        } else if (type.equals("dbms")) {
            query = new QueryToDBMS(queryElement.get("q").getAsString());
        }

        queries.put(queryName, query);
    }

    LinkedList<String> queriesNames = new LinkedList<String>(queries.keySet());
    Collections.sort(queriesNames);

    Options options = new Options();
    options.addOption(OptionBuilder.isRequired(true).withLongOpt("query").hasArg(true)
            .withDescription("The name of the query. Possible queries are: " + queriesNames).create('q'));

    options.addOption(OptionBuilder.isRequired(false).withLongOpt("args").hasArg(true)
            .withDescription("Arguments for the query").create('a'));

    options.addOption(new Option("?", "help", false, "Print this message"));

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        printHelpAndExit(options);
    }

    if (cmd.hasOption("help")) {
        printHelpAndExit(options);
    }

    String queryName = cmd.getOptionValue("q");
    String argsCmd = cmd.getOptionValue("a");

    Properties configuration = ConfigurationUtils.loadConfiguration();

    Query query = queries.get(queryName);
    if (query == null) {
        printHelpAndExit(options);
    }

    System.out.println(query.exec(argsCmd, configuration));

}

From source file:org.ala.dao.CassandraPelopsHelper.java

public static void main(String[] args) throws Exception {
    CassandraPelopsHelper helper = new CassandraPelopsHelper();
    helper.init();/*  w  w  w  . j  a v  a2s.  c o  m*/

    Map<String, Object> map = helper.getSubColumnsByGuid("tc", "103067807");
    Set<String> keys = map.keySet();
    Iterator<String> it = keys.iterator();
    while (it.hasNext()) {
        String key = it.next();
        ColumnType type = ColumnType.getColumnType(key);
        Object o = map.get(type.getColumnName());
        if (o instanceof List) {
            List l = (List) o;
        } else {
            Comparable c = (Comparable) o;
        }
    }

    /*
          TaxonConcept t = null;
           List<Comparable> l = new ArrayList<Comparable>();
            
          for(int i=0; i< 10; i++){
               t =  new TaxonConcept();
               t.setId(i);
               t.setGuid("urn:lsid:"+i);
               t.setNameString("Aus bus");
               t.setAuthor("Smith");
               t.setAuthorYear("2008");
               t.setInfoSourceName("AFD");
               t.setInfoSourceURL("http://afd.org.au");
               helper.putSingle("taxonConcept", "tc", "taxonConcept", t.getGuid(), t);
            
               l.add(t);
               if(i % 1000==0){
      System.out.println("id: "+i);
               }
          }
          helper.putList("taxonConcept", "tc", "taxonConcept", "128", l, true);
            
            CommonName c1 = new CommonName();
            c1.setNameString("Dave");
            
            CommonName c2 = new CommonName();
            c2.setNameString("Frank");
            
            helper.putSingle("taxonConcept", "tc", "taxonConcept", "123", t);
            helper.put("taxonConcept", "tc", "commonName", "123", c1);
            helper.put("taxonConcept", "tc", "commonName", "123", c2);
            helper.putSingle("taxonConcept", "tc", "taxonConcept", "124", t);
            
            TaxonConcept tc = (TaxonConcept) helper.get("taxonConcept", "tc", "taxonConcept", "123", TaxonConcept.class);
            System.out.println("Retrieved: "+tc.getNameString());
            
            List<CommonName> cns = (List) helper.getList("taxonConcept", "tc", "commonName", "123", CommonName.class);
            System.out.println("Retrieved: "+cns);
    */
    //cassandra scanning
    Scanner scanner = helper.getScanner("taxonConcept", "tc", "taxonConcept");
    for (int i = 0; i < 10; i++) {
        System.out.println(new String(scanner.getNextGuid()));
    }
    System.exit(0);
}