Example usage for java.util List forEach

List of usage examples for java.util List forEach

Introduction

In this page you can find the example usage for java.util List forEach.

Prototype

default void forEach(Consumer<? super T> action) 

Source Link

Document

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Usage

From source file:io.rhiot.spec.IoTSpec.java

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

    CommandLineParser parser = new DefaultParser();

    Options options = new Options();
    options.addOption(Option.builder("c").longOpt(CONFIG).desc(
            "Location of the test configuration file. A default value is 'src/main/resources/test.yaml' for easy IDE testing")
            .hasArg().build());/*from www.  j  a va2 s  .  co m*/

    options.addOption(Option.builder("i").longOpt(INSTANCE).desc("Instance of the test; A default value is 1")
            .hasArg().build());

    options.addOption(Option.builder("r").longOpt(REPORT)
            .desc("Location of the test report. A default value is 'target/report.csv'").hasArg().build());

    CommandLine line = parser.parse(options, args);
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    TestProfile test = mapper.readValue(new File(line.getOptionValue(CONFIG, "src/main/resources/test.yaml")),
            TestProfile.class);
    int instance = Integer.valueOf(line.getOptionValue(INSTANCE, "1"));
    test.setInstance(instance);
    String report = line.getOptionValue(REPORT, "target/report.csv");
    test.setReport(new CSVReport(report));

    LOG.info("Test '" + test.getName() + "' instance " + instance + " started");
    final List<Driver> drivers = test.getDrivers();
    ExecutorService executorService = Executors.newFixedThreadPool(drivers.size());
    List<Future<Void>> results = executorService.invokeAll(drivers, test.getDuration(), TimeUnit.MILLISECONDS);
    executorService.shutdownNow();
    executorService.awaitTermination(5, TimeUnit.SECONDS);

    results.forEach(result -> {
        try {
            result.get();
        } catch (ExecutionException execution) {
            LOG.warn("Exception running driver", execution);
        } catch (Exception interrupted) {
        }
    });

    drivers.forEach(driver -> {
        driver.stop();

        try {
            test.getReport().print(driver);
        } catch (Exception e) {
            LOG.warn("Failed to write reports for the driver " + driver);
        }
        LOG.debug("Driver " + driver);
        LOG.debug("\t " + driver.getResult());
    });
    test.getReport().close();

    LOG.info("Test '" + test.getName() + "' instance " + instance + " finished");

}

From source file:io.fabric8.vertx.maven.plugin.FileFilterMain.java

public static void main(String[] args) {

    Commandline commandline = new Commandline();
    commandline.setExecutable("java");
    commandline.createArg().setValue("io.vertx.core.Launcher");
    commandline.createArg().setValue("--redeploy=target/**/*");

    System.out.println(commandline);/*  w w w.  j  av  a  2 s . co  m*/

    File baseDir = new File("/Users/kameshs/git/fabric8io/vertx-maven-plugin/samples/vertx-demo");
    List<String> includes = new ArrayList<>();
    includes.add("src/**/*.java");
    //FileAlterationMonitor monitor  = null;
    try {

        Set<Path> inclDirs = new HashSet<>();

        includes.forEach(s -> {
            try {

                if (s.startsWith("**")) {
                    Path rootPath = Paths.get(baseDir.toString());
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                } else if (s.contains("**")) {
                    String root = s.substring(0, s.indexOf("/**"));
                    Path rootPath = Paths.get(baseDir.toString(), root);
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                }

                List<Path> dirs = FileUtils.getFileAndDirectoryNames(baseDir, s, null, true, true, true, true)
                        .stream().map(FileUtils::dirname).map(Paths::get)
                        .filter(p -> Files.exists(p) && Files.isDirectory(p)).collect(Collectors.toList());

                inclDirs.addAll(dirs);

            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        FileAlterationMonitor monitor = fileWatcher(inclDirs);

        Runnable monitorTask = () -> {
            try {
                monitor.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        monitorTask.run();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:io.reactiverse.vertx.maven.plugin.FileFilterMain.java

public static void main(String[] args) {

    Commandline commandline = new Commandline();
    commandline.setExecutable("java");
    commandline.createArg().setValue("io.vertx.core.Launcher");
    commandline.createArg().setValue("--redeploy=target/**/*");

    System.out.println(commandline);/*from  w w w  .jav a  2  s.  com*/

    File baseDir = new File("/Users/kameshs/git/reactiverse/vertx-maven-plugin/samples/vertx-demo");
    List<String> includes = new ArrayList<>();
    includes.add("src/**/*.java");
    //FileAlterationMonitor monitor  = null;
    try {

        Set<Path> inclDirs = new HashSet<>();

        includes.forEach(s -> {
            try {

                if (s.startsWith("**")) {
                    Path rootPath = Paths.get(baseDir.toString());
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                } else if (s.contains("**")) {
                    String root = s.substring(0, s.indexOf("/**"));
                    Path rootPath = Paths.get(baseDir.toString(), root);
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                }

                List<Path> dirs = FileUtils.getFileAndDirectoryNames(baseDir, s, null, true, true, true, true)
                        .stream().map(FileUtils::dirname).map(Paths::get)
                        .filter(p -> Files.exists(p) && Files.isDirectory(p)).collect(Collectors.toList());

                inclDirs.addAll(dirs);

            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        FileAlterationMonitor monitor = fileWatcher(inclDirs);

        Runnable monitorTask = () -> {
            try {
                monitor.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        monitorTask.run();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:Main.java

public static void main(String[] args) {

    List<String> friends = Arrays.asList("A", "B", "C", "D");

    //external iterate with index == evil
    for (int i = 0; i < friends.size(); i++) {
        System.out.println(friends.get(i));
    }//from  w  w  w.j a va  2s . c om

    //external iterate on collection, better but ... external
    for (String friend : friends) {
        System.out.println(friend);
    }

    //lambda
    friends.forEach(s -> System.out.println(s));

    //lambda reference
    friends.forEach(System.out::println);
}

From source file:org.neo4j.nlp.examples.wikipedia.main.java

public static void main(String[] args) throws IOException {
    List<Map<String, Object>> results = getWikipediaArticles();

    results = results.stream().filter(a -> !a.get("title").toString().trim().isEmpty())
            .collect(Collectors.toList());
    //System.out.println(results);
    // Train model
    results.forEach(row -> {
        System.out.println("Training on '" + row.get("title").toString() + "'");
        String articleText = getArticleText(row.get("title").toString());
        if (articleText != null) {
            trainOnText(new String[] { (String) articleText }, new String[] { (String) row.get("title") });
        }/*from  w  ww  . j a  v a2 s .  com*/

    });

    //System.out.println(results);
    //        try {
    //            Thread.sleep(10);
    //        } catch (InterruptedException e) {
    //            e.printStackTrace();
    //        }
}

From source file:Main.java

public static void main(String[] args) {
    List<Integer> l = Arrays.asList(1, 3, 2, 4, 7, 8, 9, 6, 5);
    int variableOutside = 50;
    Consumer<Integer> consumer = i -> { //Type of i can be implicitly known
        int variableInside = 70;
        variableInside++;//from  w ww.j a  v  a 2 s .  co  m
        System.out.printf("%d plus %d plus %d equals %d\n", variableOutside, variableInside, i,
                variableOutside + variableInside + i);
    };
    //variableOutside = 100; //Must be effectively final

    l.forEach(consumer);
}

From source file:net.e2.bw.idreg.db2ldif.Db2Ldif.java

/**
 * Main method/*from  w w w.j  a  va 2  s. c  o  m*/
 * @param args runtime arguments
 */
public static void main(String[] args) throws Exception {
    Db2Ldif db2ldif = new Db2Ldif();

    // Preload company data from json file
    ObjectMapper mapper = new ObjectMapper();
    List<Company> companies = mapper.readValue(Db2Ldif.class.getResource("/companies.json"),
            new TypeReference<List<Company>>() {
            });
    companies.forEach(c -> db2ldif.companyData.put(c.uid, c));

    new JCommander(db2ldif, args);
    db2ldif.execute();
}

From source file:Main.java

public static void main(String[] args) {
    List<Integer> l = Arrays.asList(1, 3, 2, 4, 7, 8, 9, 6, 5);
    IntWrapper variableOutside = new IntWrapper(50);
    Consumer<Integer> consumer = i -> {
        int variableInside = 70;
        System.out.println(variableOutside.getInt());
        variableOutside.incr(); // Imagine multi-thread environment calling this
        variableInside++;//from  www .j  a v a  2s  .c o  m
        System.out.printf("%s plus %d plus %d equals %d\n", variableOutside, variableInside, i,
                variableOutside.getInt() + variableInside + i);
    };
    variableOutside.incr(); // Now it's the variableOutside starts from 51
    l.forEach(consumer);
}

From source file:com.khartec.waltz.jobs.sample.EndUserAppMaker.java

public static void main(String[] args) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class);
    OrganisationalUnitDao organisationalUnitDao = ctx.getBean(OrganisationalUnitDao.class);

    DSLContext dsl = ctx.getBean(DSLContext.class);

    EndUserAppService endUserService = ctx.getBean(EndUserAppService.class);

    List<Long> ids = IdUtilities.toIds(organisationalUnitDao.findAll());

    String[] subjects = { "Trade", "Risk", "Balance", "PnL", "Rate", "Fines", "Party", "Confirmations",
            "Settlement", "Instruction", "Person", "Profit", "Margin", "Finance", "Account" };

    String[] types = { "Report", "Summary", "Draft", "Calculations", "Breaks", "Record", "Statement",
            "Information", "Pivot" };

    String[] tech = { "MS ACCESS", "MS EXCEL", "VBA" };

    dsl.delete(END_USER_APPLICATION).execute();
    final Long[] idCounter = { 1L };
    ids.forEach(ouId -> {
        for (int i = 0; i < new Random().nextInt(100) + 40; i++) {
            EndUserApplicationRecord record = dsl.newRecord(END_USER_APPLICATION);
            String name = new StringBuilder().append(randomPick(subjects)).append(" ")
                    .append(randomPick(subjects)).append(" ").append(randomPick(types)).append(" ")
                    .append(randomPick(types)).toString();

            record.setName(name);/*from   ww w .  j  a  va  2  s  . c om*/
            record.setDescription("About the " + name + " End user app");
            record.setKind(randomPick(tech));
            record.setRiskRating(randomPick(RiskRating.values()).name());
            record.setLifecyclePhase(randomPick(LifecyclePhase.values()).name());
            record.setOrganisationalUnitId(ouId);

            record.setId(idCounter[0]++);
            record.insert();
        }
    });

}

From source file:com.example.geomesa.kafka08.KafkaLoadTester.java

public static void main(String[] args) throws Exception {
    // read command line args for a connection to Kafka
    CommandLineParser parser = new BasicParser();
    Options options = getCommonRequiredOptions();
    CommandLine cmd = parser.parse(options, args);
    String visibility = getVisibility(cmd);

    if (visibility == null) {
        System.out.println("visibility: null");
    } else {/*from   w  w w  . ja v  a  2 s . com*/
        System.out.println("visibility: '" + visibility + "'");
    }

    // create the producer and consumer KafkaDataStore objects
    Map<String, String> dsConf = getKafkaDataStoreConf(cmd);
    System.out.println("KDS config: " + dsConf);
    dsConf.put("isProducer", "true");
    DataStore producerDS = DataStoreFinder.getDataStore(dsConf);
    dsConf.put("isProducer", "false");
    DataStore consumerDS = DataStoreFinder.getDataStore(dsConf);

    // verify that we got back our KafkaDataStore objects properly
    if (producerDS == null) {
        throw new Exception("Null producer KafkaDataStore");
    }
    if (consumerDS == null) {
        throw new Exception("Null consumer KafkaDataStore");
    }

    // create the schema which creates a topic in Kafka
    // (only needs to be done once)
    final String sftName = "KafkaStressTest";
    final String sftSchema = "name:String,age:Int,step:Double,lat:Double,dtg:Date,*geom:Point:srid=4326";
    SimpleFeatureType sft = SimpleFeatureTypes.createType(sftName, sftSchema);
    // set zkPath to default if not specified
    String zkPath = (dsConf.get(ZK_PATH) == null) ? "/geomesa/ds/kafka" : dsConf.get(ZK_PATH);
    SimpleFeatureType preppedOutputSft = KafkaDataStoreHelper.createStreamingSFT(sft, zkPath);
    // only create the schema if it hasn't been created already
    if (!Arrays.asList(producerDS.getTypeNames()).contains(sftName))
        producerDS.createSchema(preppedOutputSft);

    System.out.println("Register KafkaDataStore in GeoServer (Press enter to continue)");
    System.in.read();

    // the live consumer must be created before the producer writes features
    // in order to read streaming data.
    // i.e. the live consumer will only read data written after its instantiation
    SimpleFeatureStore producerFS = (SimpleFeatureStore) producerDS.getFeatureSource(sftName);
    SimpleFeatureSource consumerFS = consumerDS.getFeatureSource(sftName);

    // creates and adds SimpleFeatures to the producer every 1/5th of a second
    System.out.println("Writing features to Kafka... refresh GeoServer layer preview to see changes");

    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(sft);

    Integer numFeats = getLoad(cmd);

    System.out.println("Building a list of " + numFeats + " SimpleFeatures.");
    List<SimpleFeature> features = IntStream.range(1, numFeats)
            .mapToObj(i -> createFeature(builder, i, visibility)).collect(Collectors.toList());

    // set variables to estimate feature production rate
    Long startTime = null;
    Long featuresSinceStartTime = 0L;
    int cycle = 0;
    int cyclesToSkip = 50000 / numFeats; // collect enough features
                                         // to get an accurate rate estimate

    while (true) {
        // write features
        features.forEach(feat -> {
            try {
                DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();
                featureCollection.add(feat);
                producerFS.addFeatures(featureCollection);
            } catch (Exception e) {
                System.out.println("Caught an exception while writing features.");
                e.printStackTrace();
            }
            updateFeature(feat);
        });

        // count features written
        Integer consumerSize = consumerFS.getFeatures().size();
        cycle++;
        featuresSinceStartTime += consumerSize;
        System.out.println("At " + new Date() + " wrote " + consumerSize + " features");

        // if we've collected enough features, calculate the rate
        if (cycle >= cyclesToSkip || startTime == null) {
            Long endTime = System.currentTimeMillis();
            if (startTime != null) {
                Long diffTime = endTime - startTime;
                Double rate = (featuresSinceStartTime.doubleValue() * 1000.0) / diffTime.doubleValue();
                System.out.printf("%.1f feats/sec (%d/%d)\n", rate, featuresSinceStartTime, diffTime);
            }
            cycle = 0;
            startTime = endTime;
            featuresSinceStartTime = 0L;
        }
    }
}