List of usage examples for java.util Map entrySet
Set<Map.Entry<K, V>> entrySet();
From source file:com.seavus.wordcountermaven.WordCounter.java
/** * @param args the command line arguments * @throws java.io.FileNotFoundException *///from www. j a v a 2 s .co m public static void main(String[] args) throws FileNotFoundException { InputStream fileStream = WordCounter.class.getClassLoader().getResourceAsStream("test.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(fileStream)); Map<String, Integer> wordMap = new HashMap<>(); String line; boolean tokenFound = false; try { while ((line = br.readLine()) != null) { String[] tokens = line.trim().split("\\s+"); //trims surrounding whitespaces and splits lines into tokens for (String token : tokens) { for (Map.Entry<String, Integer> entry : wordMap.entrySet()) { if (StringUtils.equalsIgnoreCase(token, entry.getKey())) { wordMap.put(entry.getKey(), (wordMap.get(entry.getKey()) + 1)); tokenFound = true; } } if (!token.equals("") && !tokenFound) { wordMap.put(token.toLowerCase(), 1); } tokenFound = false; } } br.close(); } catch (IOException ex) { Logger.getLogger(WordCounter.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("string : " + "frequency\r\n" + "-------------------"); //prints out each unique word (i.e. case-insensitive string token) and its frequency to the console for (Map.Entry<String, Integer> entry : wordMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } }
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 ww .j av a 2 s. c o 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:Main.java
public static void main(String[] args) throws Exception { InputSource source = new InputSource(new StringReader("<root>\n" + "<field name='firstname'>\n" + " <value>John</value>\n" + "</field>\n" + "<field name='lastname'>\n" + " <value>Citizen</value>\n" + "</field>\n" + "<field name='DoB'>\n" + " <value>01/01/1980</value>\n" + "</field>\n" + "<field name='Profession'>\n" + " <value>Manager</value>\n" + "</field>\n" + "</root>")); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); Document document = documentBuilder.parse(source); NodeList allFields = (NodeList) document.getElementsByTagName("field"); Map<String, String> data = new HashMap<>(); for (int i = 0; i < allFields.getLength(); i++) { Element field = (Element) allFields.item(i); String nameAttribute = field.getAttribute("name"); Element child = (Element) field.getElementsByTagName("value").item(0); String value = child.getTextContent(); data.put(nameAttribute, value);/*from w w w . j a v a 2 s.c o m*/ } for (Map.Entry field : data.entrySet()) { System.out.println(field.getKey() + ": " + field.getValue()); } }
From source file:common.ReverseWordsCount.java
public static void main(String[] args) throws IOException { List<String> readLines = FileUtils.readLines(new File("G:\\\\LTNMT\\LTNMT\\sougou\\sougou2500.txt")); Map<String, Integer> words = new HashMap<>(); for (String line : readLines) { String[] split = line.split(" "); for (String wprd : split) { Integer get = words.get(wprd); if (get == null) { words.put(wprd, 1);/*from w w w . j av a 2s . c o m*/ } else { words.put(wprd, get + 1); } } } Set<Map.Entry<String, Integer>> entrySet = words.entrySet(); List<Map.Entry<String, Integer>> reverseLists = new ArrayList<>(entrySet); Collections.sort(reverseLists, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o2.getValue().compareTo(o1.getValue()); } }); PrintStream ps = new PrintStream("c:/reverseWords.txt"); for (Map.Entry<String, Integer> teEntry : reverseLists) { ps.println(teEntry.getKey() + " " + teEntry.getValue()); } ps.close(); }
From source file:com.act.biointerpretation.l2expansion.L2FilteringDriver.java
public static void main(String[] args) throws Exception { // Build command line parser. Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/*w w w .ja v a 2 s.c o m*/ } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { LOGGER.error("Argument parsing failed: %s", e.getMessage()); HELP_FORMATTER.printHelp(L2FilteringDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } // Print help. if (cl.hasOption(OPTION_HELP)) { HELP_FORMATTER.printHelp(L2FilteringDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } checkFilterOptionIsValid(OPTION_CHEMICAL_FILTER, cl); checkFilterOptionIsValid(OPTION_REACTION_FILTER, cl); // Get corpus files. File corpusFile = new File(cl.getOptionValue(OPTION_INPUT_CORPUS)); if (!corpusFile.exists()) { LOGGER.error("Input corpus file does not exist."); return; } File outputFile = new File(cl.getOptionValue(OPTION_OUTPUT_PATH)); outputFile.createNewFile(); if (outputFile.isDirectory()) { LOGGER.error("Output file is directory."); System.exit(1); } LOGGER.info("Reading corpus from file."); L2PredictionCorpus predictionCorpus = L2PredictionCorpus.readPredictionsFromJsonFile(corpusFile); LOGGER.info("Read in corpus with %d predictions.", predictionCorpus.getCorpus().size()); LOGGER.info("Corpus has %d distinct substrates.", predictionCorpus.getUniqueSubstrateInchis().size()); if (cl.hasOption(OPTION_FILTER_SUBSTRATES)) { LOGGER.info("Filtering by substrates."); File substratesFile = new File(cl.getOptionValue(OPTION_FILTER_SUBSTRATES)); L2InchiCorpus inchis = new L2InchiCorpus(); inchis.loadCorpus(substratesFile); Set<String> inchiSet = new HashSet<String>(); inchiSet.addAll(inchis.getInchiList()); predictionCorpus = predictionCorpus .applyFilter(prediction -> inchiSet.containsAll(prediction.getSubstrateInchis())); predictionCorpus.writePredictionsToJsonFile(outputFile); LOGGER.info("Done writing filtered corpus to file."); return; } if (cl.hasOption(OPTION_SPLIT_BY_RO)) { LOGGER.info("Splitting corpus into distinct corpuses for each ro."); Map<String, L2PredictionCorpus> corpusMap = predictionCorpus .splitCorpus(prediction -> prediction.getProjectorName()); for (Map.Entry<String, L2PredictionCorpus> entry : corpusMap.entrySet()) { String fileName = cl.getOptionValue(OPTION_OUTPUT_PATH) + "." + entry.getKey(); File oneOutputFile = new File(fileName); entry.getValue().writePredictionsToJsonFile(oneOutputFile); } LOGGER.info("Done writing split corpuses to file."); return; } predictionCorpus = runDbLookups(cl, predictionCorpus, opts); LOGGER.info("Applying filters."); predictionCorpus = applyFilter(predictionCorpus, ALL_CHEMICALS_IN_DB, cl, OPTION_CHEMICAL_FILTER); predictionCorpus = applyFilter(predictionCorpus, REACTION_MATCHES_DB, cl, OPTION_REACTION_FILTER); LOGGER.info("Filtered corpus has %d predictions.", predictionCorpus.getCorpus().size()); LOGGER.info("Printing final corpus."); predictionCorpus.writePredictionsToJsonFile(outputFile); LOGGER.info("L2FilteringDriver complete!."); }
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());//from w w w .j a va 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:com.act.lcms.db.io.report.IonAnalysisInterchangeModelOperations.java
public static void main(String[] args) throws IOException { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());//from ww w .jav a 2s . com } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { LOGGER.error("Argument parsing failed: %s", e.getMessage()); HELP_FORMATTER.printHelp(IonAnalysisInterchangeModelOperations.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(IonAnalysisInterchangeModelOperations.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption(OPTION_LOG_DISTRIBUTION)) { IonAnalysisInterchangeModel model = new IonAnalysisInterchangeModel(); model.loadResultsFromFile(new File(cl.getOptionValue(OPTION_INPUT_FILE))); Map<Pair<Double, Double>, Integer> rangeToCount = model .computeLogFrequencyDistributionOfMoleculeCountToMetric( IonAnalysisInterchangeModel.METRIC.valueOf(cl.getOptionValue(OPTION_LOG_DISTRIBUTION))); try (BufferedWriter predictionWriter = new BufferedWriter( new FileWriter(new File(OPTION_OUTPUT_FILE)))) { for (Map.Entry<Pair<Double, Double>, Integer> entry : rangeToCount.entrySet()) { String value = String.format("%f,%d", entry.getKey().getLeft(), entry.getValue()); predictionWriter.write(value); predictionWriter.newLine(); } } } }
From source file:Main.java
public static void main(String[] args) { Map<Month, String> dobCalendar = Employee.persons().stream() .collect(Collectors.collectingAndThen(Collectors.groupingBy(p -> p.getDob().getMonth(), Collectors.mapping(Employee::getName, Collectors.joining(" "))), result -> { for (Month m : Month.values()) { result.putIfAbsent(m, "None"); }//from w w w . j a v a 2 s . c o m return Collections.unmodifiableMap(new TreeMap<>(result)); })); dobCalendar.entrySet().forEach(System.out::println); }
From source file:edu.brown.benchmark.seats.util.GenerateHistograms.java
public static void main(String[] vargs) throws Exception { ArgumentsParser args = ArgumentsParser.load(vargs); File csv_path = new File(args.getOptParam(0)); File output_path = new File(args.getOptParam(1)); GenerateHistograms gh = GenerateHistograms.generate(csv_path); Map<String, Object> m = new ListOrderedMap<String, Object>(); m.put("Airport Codes", gh.flights_per_airport.size()); m.put("Airlines", gh.flights_per_airline.getValueCount()); m.put("Departure Times", gh.flights_per_time.getValueCount()); LOG.info(StringUtil.formatMaps(m));/*from w w w . j a v a 2 s . co m*/ System.err.println(StringUtil.join("\n", gh.flights_per_airport.keySet())); Map<String, Histogram<?>> histograms = new HashMap<String, Histogram<?>>(); histograms.put(SEATSConstants.HISTOGRAM_FLIGHTS_PER_DEPART_TIMES, gh.flights_per_time); // histograms.put(SEATSConstants.HISTOGRAM_FLIGHTS_PER_AIRLINE, gh.flights_per_airline); histograms.put(SEATSConstants.HISTOGRAM_FLIGHTS_PER_AIRPORT, SEATSHistogramUtil.collapseAirportFlights(gh.flights_per_airport)); for (Entry<String, Histogram<?>> e : histograms.entrySet()) { File output_file = new File(output_path.getAbsolutePath() + "/" + e.getKey() + ".histogram"); LOG.info(String.format("Writing out %s data to '%s' [samples=%d, values=%d]", e.getKey(), output_file, e.getValue().getSampleCount(), e.getValue().getValueCount())); e.getValue().save(output_file); } // FOR }
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()); }//www.j ava2s. c om }