Example usage for java.util Map entrySet

List of usage examples for java.util Map entrySet

Introduction

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

Prototype

Set<Map.Entry<K, V>> entrySet();

Source Link

Document

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

Usage

From source file:Main.java

public static void main(String[] args) {
    List<Person> roster = createRoster();

    System.out.println("Total age by gender:");
    Map<Person.Sex, Integer> totalAgeByGender = roster.stream().collect(
            Collectors.groupingBy(Person::getGender, Collectors.reducing(0, Person::getAge, Integer::sum)));

    List<Map.Entry<Person.Sex, Integer>> totalAgeByGenderList = new ArrayList<>(totalAgeByGender.entrySet());

    totalAgeByGenderList.stream()//from www.  j av  a  2  s  .com
            .forEach(e -> System.out.println("Gender: " + e.getKey() + ", Total Age: " + e.getValue()));

}

From source file:com.couchbase.roadrunner.RoadRunner.java

/**
 * Initialize the RoadRunner./*from  w ww.  j  a v a 2s  .  c om*/
 *
 * This method is responsible for parsing the passed in command line arguments
 * and also dispatch the bootstrapping of the actual workload runner.
 *
 * @param args Command line arguments to be passed in.
 */
public static void main(final String[] args) {
    CommandLine params = null;
    try {
        params = parseCommandLine(args);
    } catch (ParseException ex) {
        LOGGER.error("Exception while parsing command line!", ex);
        System.exit(-1);
    }

    if (params.hasOption(OPT_HELP)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("roadrunner", getCommandLineOptions());
        System.exit(0);
    }

    GlobalConfig config = GlobalConfig.fromCommandLine(params);
    WorkloadDispatcher dispatcher = new WorkloadDispatcher(config);

    LOGGER.info("Running with Config: " + config.toString());

    try {
        LOGGER.debug("Initializing ClientHandlers.");
        dispatcher.init();
    } catch (Exception ex) {
        LOGGER.error("Error while initializing the ClientHandlers: ", ex);
        System.exit(-1);
    }

    Stopwatch workloadStopwatch = new Stopwatch().start();
    try {
        LOGGER.info("Running Workload.");
        dispatcher.dispatchWorkload();
    } catch (Exception ex) {
        LOGGER.error("Error while running the Workload: ", ex);
        System.exit(-1);
    }
    workloadStopwatch.stop();

    LOGGER.debug("Finished Workload.");

    LOGGER.info("==== RESULTS ====");

    dispatcher.prepareMeasures();

    long totalOps = dispatcher.getTotalOps();
    long measuredOps = dispatcher.getMeasuredOps();

    LOGGER.info("Operations: measured " + measuredOps + "ops out of total " + totalOps + "ops.");

    Map<String, List<Stopwatch>> measures = dispatcher.getMeasures();
    for (Map.Entry<String, List<Stopwatch>> entry : measures.entrySet()) {
        Histogram h = new Histogram(60 * 60 * 1000, 5);
        for (Stopwatch watch : entry.getValue()) {
            h.recordValue(watch.elapsed(TimeUnit.MICROSECONDS));
        }

        LOGGER.info("Percentile (microseconds) for \"" + entry.getKey() + "\" Workload:");
        LOGGER.info("   50%:" + (Math.round(h.getValueAtPercentile(0.5) * 100) / 100) + "   75%:"
                + (Math.round(h.getValueAtPercentile(0.75) * 100) / 100) + "   95%:"
                + (Math.round(h.getValueAtPercentile(0.95) * 100) / 100) + "   99%:"
                + (Math.round(h.getValueAtPercentile(0.99) * 100) / 100));
    }

    LOGGER.info("Elapsed: " + workloadStopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms");

    List<Stopwatch> elapsedThreads = dispatcher.getThreadElapsed();
    long shortestThread = 0;
    long longestThread = 0;
    for (Stopwatch threadWatch : elapsedThreads) {
        long threadMs = threadWatch.elapsed(TimeUnit.MILLISECONDS);
        if (longestThread == 0 || threadMs > longestThread) {
            longestThread = threadMs;
        }
        if (shortestThread == 0 || threadMs < shortestThread) {
            shortestThread = threadMs;
        }
    }

    LOGGER.info("Shortest Thread: " + shortestThread + "ms");
    LOGGER.info("Longest Thread: " + longestThread + "ms");

}

From source file:Main.java

public static void main(String[] args) {
    List<Person> roster = createRoster();

    System.out.println("Names by gender:");
    Map<Person.Sex, List<String>> namesByGender = roster.stream().collect(
            Collectors.groupingBy(Person::getGender, Collectors.mapping(Person::getName, Collectors.toList())));

    List<Map.Entry<Person.Sex, List<String>>> namesByGenderList = new ArrayList<>(namesByGender.entrySet());

    namesByGenderList.stream().forEach(e -> {
        System.out.println("Gender: " + e.getKey());
        e.getValue().stream().forEach(f -> System.out.println(f));
    });//  ww  w .jav a2  s  . c  om

}

From source file:Main.java

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

    String blah = "aaaabbbbddd";

    for (int i = 0; i < blah.length(); i++) {
        char c = blah.charAt(i);
        if (!map.containsKey(c)) {
            map.put(c, 1);//from ww  w  .j a  v  a  2 s  .c  o  m
        } else {
            map.put(c, (map.get(c) + 1));
        }
    }

    for (Map.Entry<Character, Integer> entry : map.entrySet()) {
        System.out.print(entry.getKey() + "" + entry.getValue());
    }
}

From source file:com.jkoolcloud.tnt4j.streams.sample.builder.SampleStreamingApp.java

/**
 * Main entry point for running as a standalone application.
 *
 * @param args//  w  ww  . j  a  va  2  s  .c  o  m
 *            program command-line arguments. Supported arguments:
 *            <table summary="TNT4J-Streams agent command line arguments">
 *            <tr>
 *            <td>&nbsp;&nbsp;</td>
 *            <td>&nbsp;&lt;orders_log_file_path&gt;</td>
 *            <td>(optional) path of "orders.log" file. Default value is working dir.</td>
 *            </tr>
 *            </table>
 * @throws Exception
 *             if any exception occurs while running application
 */
public static void main(String... args) throws Exception {
    Map<String, String> props = new HashMap<>();
    props.put(ParserProperties.PROP_FLD_DELIM, "|"); // NON-NLS

    ActivityTokenParser atp = new ActivityTokenParser();
    atp.setName("TokenParser"); // NON-NLS
    atp.setProperties(props.entrySet());

    ActivityField f = new ActivityField(StreamFieldType.StartTime.name());
    ActivityFieldLocator afl = new ActivityFieldLocator(ActivityFieldLocatorType.Index, "1");
    afl.setFormat("dd MMM yyyy HH:mm:ss", "en-US"); // NON-NLS
    f.addLocator(afl);
    atp.addField(f);

    f = new ActivityField(StreamFieldType.ServerIp.name());
    afl = new ActivityFieldLocator(ActivityFieldLocatorType.Index, "2");
    f.addLocator(afl);
    atp.addField(f);

    f = new ActivityField(StreamFieldType.ApplName.name());
    afl = new ActivityFieldLocator("orders"); // NON-NLS
    f.addLocator(afl);
    atp.addField(f);

    f = new ActivityField(StreamFieldType.Correlator.name());
    afl = new ActivityFieldLocator(ActivityFieldLocatorType.Index, "3");
    f.addLocator(afl);
    atp.addField(f);

    f = new ActivityField(StreamFieldType.UserName.name());
    afl = new ActivityFieldLocator(ActivityFieldLocatorType.Index, "4");
    f.addLocator(afl);
    atp.addField(f);

    f = new ActivityField(StreamFieldType.EventName.name());
    afl = new ActivityFieldLocator(ActivityFieldLocatorType.Index, "5");
    f.addLocator(afl);
    atp.addField(f);

    f = new ActivityField(StreamFieldType.EventType.name());
    afl = new ActivityFieldLocator(ActivityFieldLocatorType.Index, "5");
    afl.addValueMap("Order Placed", "START").addValueMap("Order Received", "RECEIVE") // NON-NLS
            .addValueMap("Order Processing", "OPEN").addValueMap("Order Processed", "SEND") // NON-NLS
            .addValueMap("Order Shipped", "END"); // NON-NLS
    f.addLocator(afl);
    atp.addField(f);

    f = new ActivityField("MsgValue"); // NON-NLS
    afl = new ActivityFieldLocator(ActivityFieldLocatorType.Index, "8");
    f.addLocator(afl);
    atp.addField(f);

    props = new HashMap<>();
    props.put(StreamProperties.PROP_FILENAME, ArrayUtils.isEmpty(args) ? "orders.log" : args[0]); // NON-NLS

    FileLineStream fls = new FileLineStream();
    fls.setName("FileStream"); // NON-NLS
    fls.setProperties(props.entrySet());
    fls.addParser(atp);
    // if (fls.getOutput() == null) {
    // fls.setDefaultStreamOutput();
    // }

    StreamsAgent.runFromAPI(fls);
}

From source file:com.glaf.core.util.JsonUtils.java

public static void main(String[] args) throws Exception {
    Map<String, Object> dataMap = new java.util.HashMap<String, Object>();
    dataMap.put("key01", "");
    dataMap.put("key02", 12345);
    dataMap.put("key03", 789.85D);
    dataMap.put("date", new Date());
    Collection<Object> actorIds = new HashSet<Object>();
    actorIds.add("sales01");
    actorIds.add("sales02");
    actorIds.add("sales03");
    actorIds.add("sales04");
    actorIds.add("sales05");
    dataMap.put("actorIds", actorIds.toArray());
    dataMap.put("x_sale_actor_actorIds", actorIds);

    Map<String, Object> xxxMap = new java.util.HashMap<String, Object>();
    xxxMap.put("0", "--------");
    xxxMap.put("1", "?");
    xxxMap.put("2", "");
    xxxMap.put("3", "");

    dataMap.put("trans", xxxMap);

    String str = JsonUtils.encode(dataMap);
    System.out.println(str);/*w w w  .j  a va  2 s  .c o m*/
    Map<?, ?> p = JsonUtils.decode(str);
    System.out.println(p);
    System.out.println(p.get("date").getClass().getName());

    String xx = "{name:\"trans\",nodeType:\"select\",children:{\"1\":\"?\",\"3\":\"\",\"2\":\"\",\"0\":\"--------\"}}";
    Map<String, Object> xMap = JsonUtils.decode(xx);
    System.out.println(xMap);
    Set<Entry<String, Object>> entrySet = xMap.entrySet();
    for (Entry<String, Object> entry : entrySet) {
        String key = entry.getKey();
        Object value = entry.getValue();
        System.out.println(key + " = " + value);
        System.out.println(key.getClass().getName() + "  " + value.getClass().getName());
        if (value instanceof JSONObject) {
            JSONObject json = (JSONObject) value;
            Iterator<?> iter = json.keySet().iterator();
            while (iter.hasNext()) {
                String kk = (String) iter.next();
                System.out.println(kk + " = " + json.get(kk));
            }
        }
    }
}

From source file:cz.hobrasoft.pdfmu.jackson.SchemaGenerator.java

public static void main(String[] args) throws JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT); // nice formatting

    SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();

    Map<String, Type> types = new HashMap<>();
    types.put("RpcResponse", RpcResponse.class);
    types.put("result/inspect", Inspect.class);
    types.put("result/version set", VersionSet.class);
    types.put("result/signature add", SignatureAdd.class);
    types.put("result/empty", EmptyResult.class);

    for (Map.Entry<String, Type> e : types.entrySet()) {
        String name = e.getKey();
        String filename = String.format("schema/%s.json", name);
        Type type = e.getValue();
        mapper.acceptJsonFormatVisitor(mapper.constructType(type), visitor);
        JsonSchema jsonSchema = visitor.finalSchema();
        mapper.writeValue(new File(filename), jsonSchema);
    }/*from  w w  w  .ja va  2s  . c  om*/
}

From source file:Main.java

public static void main(String[] argv) {
    List collection = new ArrayList();

    // For a set or list
    for (Iterator it = collection.iterator(); it.hasNext();) {
        Object element = it.next();
    }/*ww w.jav a  2 s.  com*/
    Map map = new HashMap();
    // For keys of a map
    for (Iterator it = map.keySet().iterator(); it.hasNext();) {
        Object key = it.next();
    }

    // For values of a map
    for (Iterator it = map.values().iterator(); it.hasNext();) {
        Object value = it.next();
    }

    // For both the keys and values of a map
    for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();
        Object key = entry.getKey();
        Object value = entry.getValue();
    }
}

From source file:com.xiaoxiaomo.flink.batch.distcp.DistCp.java

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

    // set up the execution environment
    final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

    ParameterTool params = ParameterTool.fromArgs(args);
    if (!params.has("input") || !params.has("output")) {
        System.err.println("Usage: --input <path> --output <path> [--parallelism <n>]");
        return;/* w w  w .j ava  2s. c o m*/
    }

    final Path sourcePath = new Path(params.get("input"));
    final Path targetPath = new Path(params.get("output"));
    if (!isLocal(env) && !(isOnDistributedFS(sourcePath) && isOnDistributedFS(targetPath))) {
        System.out.println("In a distributed mode only HDFS input/output paths are supported");
        return;
    }

    final int parallelism = params.getInt("parallelism", 10);
    if (parallelism <= 0) {
        System.err.println("Parallelism should be greater than 0");
        return;
    }

    // make parameters available in the web interface
    env.getConfig().setGlobalJobParameters(params);

    env.setParallelism(parallelism);

    long startTime = System.currentTimeMillis();
    LOGGER.info("Initializing copy tasks");
    List<FileCopyTask> tasks = getCopyTasks(sourcePath);
    LOGGER.info("Copy task initialization took " + (System.currentTimeMillis() - startTime) + "ms");

    DataSet<FileCopyTask> inputTasks = new DataSource<FileCopyTask>(env, new FileCopyTaskInputFormat(tasks),
            new GenericTypeInfo<FileCopyTask>(FileCopyTask.class), "fileCopyTasks");

    FlatMapOperator<FileCopyTask, Object> res = inputTasks
            .flatMap(new RichFlatMapFunction<FileCopyTask, Object>() {

                private static final long serialVersionUID = 1109254230243989929L;
                private LongCounter fileCounter;
                private LongCounter bytesCounter;

                @Override
                public void open(Configuration parameters) throws Exception {
                    bytesCounter = getRuntimeContext().getLongCounter(BYTES_COPIED_CNT_NAME);
                    fileCounter = getRuntimeContext().getLongCounter(FILES_COPIED_CNT_NAME);
                }

                @Override
                public void flatMap(FileCopyTask task, Collector<Object> out) throws Exception {
                    LOGGER.info("Processing task: " + task);
                    Path outPath = new Path(targetPath, task.getRelativePath());

                    FileSystem targetFs = targetPath.getFileSystem();
                    // creating parent folders in case of a local FS
                    if (!targetFs.isDistributedFS()) {
                        //dealing with cases like file:///tmp or just /tmp
                        File outFile = outPath.toUri().isAbsolute() ? new File(outPath.toUri())
                                : new File(outPath.toString());
                        File parentFile = outFile.getParentFile();
                        if (!parentFile.mkdirs() && !parentFile.exists()) {
                            throw new RuntimeException(
                                    "Cannot create local file system directories: " + parentFile);
                        }
                    }
                    FSDataOutputStream outputStream = null;
                    FSDataInputStream inputStream = null;
                    try {
                        outputStream = targetFs.create(outPath, true);
                        inputStream = task.getPath().getFileSystem().open(task.getPath());
                        int bytes = IOUtils.copy(inputStream, outputStream);
                        bytesCounter.add(bytes);
                    } finally {
                        IOUtils.closeQuietly(inputStream);
                        IOUtils.closeQuietly(outputStream);
                    }
                    fileCounter.add(1L);
                }
            });

    // no data sinks are needed, therefore just printing an empty result
    res.print();

    Map<String, Object> accumulators = env.getLastJobExecutionResult().getAllAccumulatorResults();
    LOGGER.info("== COUNTERS ==");
    for (Map.Entry<String, Object> e : accumulators.entrySet()) {
        LOGGER.info(e.getKey() + ": " + e.getValue());
    }
}

From source file:com.edgenius.wiki.ext.textnut.NutParser.java

public static void main(String[] args) throws IOException {
    NutParser parser = new NutParser();
    //      parser.parseHTML(FileUtils.readFileToString(new File("c:/temp/a.html")));
    Map<String, File> map = parser.parseBPlist(
            new FileInputStream(new File("C:/Dapeng/Future/webarchive/TextNut.nut/20110312/P1.webarchive")));
    if (map != null) {
        for (Entry<String, File> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }/*from   w ww. j  av  a  2s  .c o m*/
        File file = map.get(MAIN_RESOURCE_URL);
        String content = parser.convertNutHTMLToPageHTML(FileUtils.readFileToString(file));
        System.out.println("=======");
        System.out.println(content);
        System.out.println("=======");
    }
}