Example usage for java.util List stream

List of usage examples for java.util List stream

Introduction

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

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

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

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

    AuthoritativeSourceDao authSourceDao = ctx.getBean(AuthoritativeSourceDao.class);
    ApplicationService applicationDao = ctx.getBean(ApplicationService.class);
    DataTypeService dataTypesDao = ctx.getBean(DataTypeService.class);
    DataFlowService dataFlowDao = ctx.getBean(DataFlowService.class);
    OrganisationalUnitService orgUnitDao = ctx.getBean(OrganisationalUnitService.class);
    DataSource dataSource = ctx.getBean(DataSource.class);
    DSLContext dsl = ctx.getBean(DSLContext.class);

    List<AuthoritativeSource> authSources = authSourceDao.findByEntityKind(EntityKind.ORG_UNIT);
    List<String> dataTypes = dataTypesDao.getAll().stream().map(dt -> dt.code()).collect(toList());
    List<Application> apps = applicationDao.findAll();
    List<OrganisationalUnit> orgUnits = orgUnitDao.findAll();

    Set<DataFlow> expectedFlows = authSources.stream().flatMap(a -> {
        long orgUnitId = a.parentReference().id();

        return IntStream.range(0, rnd.nextInt(40))
                .mapToObj(i -> ImmutableDataFlow.builder().dataType(a.dataType())
                        .source(a.applicationReference()).target(randomAppPick(apps, orgUnitId)).build());
    }).collect(Collectors.toSet());

    Set<DataFlow> probableFlows = authSources.stream().flatMap(a -> IntStream.range(0, rnd.nextInt(30))
            .mapToObj(i -> ImmutableDataFlow.builder().dataType(a.dataType()).source(a.applicationReference())
                    .target(randomAppPick(apps, randomPick(orgUnits).id().get())).build()))
            .collect(Collectors.toSet());

    Set<DataFlow> randomFlows = apps.stream()
            .map(a -> ImmutableDataFlow.builder().source(a.toEntityReference()))
            .map(b -> b.target(randomAppPick(apps, randomPick(orgUnits).id().get())))
            .map(b -> b.dataType(randomPick(dataTypes)).build()).collect(Collectors.toSet());

    dsl.deleteFrom(DATA_FLOW).execute();

    Set<DataFlow> all = new HashSet<>();
    all.addAll(randomFlows);//from  w ww.  ja v a 2s .c o m
    all.addAll(expectedFlows);
    all.addAll(probableFlows);

    dataFlowDao.addFlows(new ArrayList<>(all));

    System.out.println("Done");

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    List<Dish> menu = Arrays.asList(new Dish("pork", false, 800, Dish.Type.MEAT),
            new Dish("beef", false, 700, Dish.Type.MEAT), new Dish("chicken", false, 400, Dish.Type.MEAT),
            new Dish("rice", true, 350, Dish.Type.OTHER), new Dish("pizza", true, 550, Dish.Type.OTHER),
            new Dish("prawns", false, 400, Dish.Type.FISH), new Dish("salmon", false, 450, Dish.Type.FISH));
    Optional<Dish> vegetarianMenu = menu.stream().filter(Dish::isVegetarian).findAny();

    System.out.println(vegetarianMenu);

}

From source file:co.paralleluniverse.photon.Photon.java

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

    final Options options = new Options();
    options.addOption("rate", true, "Requests per second (default " + rateDefault + ")");
    options.addOption("duration", true,
            "Minimum test duration in seconds: will wait for <duration> * <rate> requests to terminate or, if progress check enabled, no progress after <duration> (default "
                    + durationDefault + ")");
    options.addOption("maxconnections", true,
            "Maximum number of open connections (default " + maxConnectionsDefault + ")");
    options.addOption("timeout", true,
            "Connection and read timeout in millis (default " + timeoutDefault + ")");
    options.addOption("print", true,
            "Print cycle in millis, 0 to disable intermediate statistics (default " + printCycleDefault + ")");
    options.addOption("check", true,
            "Progress check cycle in millis, 0 to disable progress check (default " + checkCycleDefault + ")");
    options.addOption("stats", false, "Print full statistics when finish (default false)");
    options.addOption("minmax", false, "Print min/mean/stddev/max stats when finish (default false)");
    options.addOption("name", true, "Test name to print in the statistics (default '" + testNameDefault + "')");
    options.addOption("help", false, "Print help");

    try {//w w  w .  j  ava 2 s . com
        final CommandLine cmd = new BasicParser().parse(options, args);
        final String[] ar = cmd.getArgs();
        if (cmd.hasOption("help") || ar.length != 1)
            printUsageAndExit(options);

        final String url = ar[0];

        final int timeout = Integer.parseInt(cmd.getOptionValue("timeout", timeoutDefault));
        final int maxConnections = Integer
                .parseInt(cmd.getOptionValue("maxconnections", maxConnectionsDefault));
        final int duration = Integer.parseInt(cmd.getOptionValue("duration", durationDefault));
        final int printCycle = Integer.parseInt(cmd.getOptionValue("print", printCycleDefault));
        final int checkCycle = Integer.parseInt(cmd.getOptionValue("check", checkCycleDefault));
        final String testName = cmd.getOptionValue("name", testNameDefault);
        final int rate = Integer.parseInt(cmd.getOptionValue("rate", rateDefault));

        final MetricRegistry metrics = new MetricRegistry();
        final Meter requestMeter = metrics.meter("request");
        final Meter responseMeter = metrics.meter("response");
        final Meter errorsMeter = metrics.meter("errors");
        final Logger log = LoggerFactory.getLogger(Photon.class);
        final ConcurrentHashMap<String, AtomicInteger> errors = new ConcurrentHashMap<>();
        final HttpGet request = new HttpGet(url);
        final StripedTimeSeries<Long> sts = new StripedTimeSeries<>(30000, false);
        final StripedHistogram sh = new StripedHistogram(60000, 5);

        log.info("name: " + testName + " url:" + url + " rate:" + rate + " duration:" + duration
                + " maxconnections:" + maxConnections + ", " + "timeout:" + timeout);
        final DefaultConnectingIOReactor ioreactor = new DefaultConnectingIOReactor(IOReactorConfig.custom()
                .setConnectTimeout(timeout).setIoThreadCount(10).setSoTimeout(timeout).build());

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            final List<ExceptionEvent> events = ioreactor.getAuditLog();
            if (events != null)
                events.stream().filter(event -> event != null).forEach(event -> {
                    System.err.println(
                            "Apache Async HTTP Client I/O Reactor Error Time: " + event.getTimestamp());
                    //noinspection ThrowableResultOfMethodCallIgnored
                    if (event.getCause() != null)
                        //noinspection ThrowableResultOfMethodCallIgnored
                        event.getCause().printStackTrace();
                });
            if (cmd.hasOption("stats"))
                printFinishStatistics(errorsMeter, sts, sh, testName);
            if (!errors.keySet().isEmpty())
                errors.entrySet().stream()
                        .forEach(p -> log.info(testName + " " + p.getKey() + " " + p.getValue() + "ms"));
            System.out.println(
                    testName + " responseTime(90%): " + sh.getHistogramData().getValueAtPercentile(90) + "ms");
            if (cmd.hasOption("minmax")) {
                final HistogramData hd = sh.getHistogramData();
                System.out.format("%s %8s%8s%8s%8s\n", testName, "min", "mean", "sd", "max");
                System.out.format("%s %8d%8.2f%8.2f%8d\n", testName, hd.getMinValue(), hd.getMean(),
                        hd.getStdDeviation(), hd.getMaxValue());
            }
        }));

        final PoolingNHttpClientConnectionManager mngr = new PoolingNHttpClientConnectionManager(ioreactor);
        mngr.setDefaultMaxPerRoute(maxConnections);
        mngr.setMaxTotal(maxConnections);
        final CloseableHttpAsyncClient ahc = HttpAsyncClientBuilder.create().setConnectionManager(mngr)
                .setDefaultRequestConfig(RequestConfig.custom().setLocalAddress(null).build()).build();
        try (final CloseableHttpClient client = new FiberHttpClient(ahc)) {
            final int num = duration * rate;

            final CountDownLatch cdl = new CountDownLatch(num);
            final Semaphore sem = new Semaphore(maxConnections);
            final RateLimiter rl = RateLimiter.create(rate);

            spawnStatisticsThread(printCycle, cdl, log, requestMeter, responseMeter, errorsMeter, testName);

            for (int i = 0; i < num; i++) {
                rl.acquire();
                if (sem.availablePermits() == 0)
                    log.debug("Maximum connections count reached, waiting...");
                sem.acquireUninterruptibly();

                new Fiber<Void>(() -> {
                    requestMeter.mark();
                    final long start = System.nanoTime();
                    try {
                        try (final CloseableHttpResponse ignored = client.execute(request)) {
                            responseMeter.mark();
                        } catch (final Throwable t) {
                            markError(errorsMeter, errors, t);
                        }
                    } catch (final Throwable t) {
                        markError(errorsMeter, errors, t);
                    } finally {
                        final long now = System.nanoTime();
                        final long millis = TimeUnit.NANOSECONDS.toMillis(now - start);
                        sts.record(start, millis);
                        sh.recordValue(millis);
                        sem.release();
                        cdl.countDown();
                    }
                }).start();
            }
            spawnProgressCheckThread(log, duration, checkCycle, cdl);
            cdl.await();
        }
    } catch (final ParseException ex) {
        System.err.println("Parsing failed.  Reason: " + ex.getMessage());
    }
}

From source file:com.bekwam.resignator.commands.KeytoolCommand.java

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

    KeytoolCommand cmd = new KeytoolCommand();

    System.out.println("****** cacerts *******");
    List<KeystoreEntry> entries = cmd.findKeystoreEntries("C:\\Program Files\\Java\\jdk1.8.0_40\\bin\\keytool",
            "C:\\Program Files\\Java\\jdk1.8.0_40\\jre\\lib\\security\\cacerts", "changeit");

    entries.stream().forEach((e) -> System.out.println(e.getAlias() + "/" + e.getFingerprint()));

    System.out.println("****** just cacerts aliases *******");
    List<String> aliases = cmd.findAliases("C:\\Program Files\\Java\\jdk1.8.0_40\\bin\\keytool",
            "C:\\Program Files\\Java\\jdk1.8.0_40\\jre\\lib\\security\\cacerts", "changeit");

    aliases.stream().forEach((a) -> System.out.println(a));

    System.out.println("****** test *******");
    entries = cmd.findKeystoreEntries("C:\\Program Files\\Java\\jdk1.8.0_40\\bin\\keytool",
            "C:\\Users\\carl_000\\git\\resignator-repos-1\\resignator\\mykeystore", "ab987c");

    entries.stream().forEach((e) -> System.out.println(e.getAlias() + "/" + e.getFingerprint()));

    System.out.println("****** just test aliases *******");
    aliases = cmd.findAliases("C:\\Program Files\\Java\\jdk1.8.0_40\\bin\\keytool",
            "C:\\Users\\carl_000\\git\\resignator-repos-1\\resignator\\mykeystore", "ab987c");

    aliases.stream().forEach((a) -> System.out.println(a));

    System.out.println("****** empty *******");
    entries = cmd.findKeystoreEntries("C:\\Program Files\\Java\\jdk1.8.0_40\\bin\\keytool",
            "C:\\Users\\carl_000\\git\\resignator-repos-1\\resignator\\emptykeystore", "ab987c");

    entries.stream().forEach((e) -> System.out.println(e.getAlias() + "/" + e.getFingerprint()));

    System.out.println("****** just empty aliases *******");
    aliases = cmd.findAliases("C:\\Program Files\\Java\\jdk1.8.0_40\\bin\\keytool",
            "C:\\Users\\carl_000\\git\\resignator-repos-1\\resignator\\emptykeystore", "ab987c");

    aliases.stream().forEach((a) -> System.out.println(a));

    System.out.println("***** bad password *****");

    entries = cmd.findKeystoreEntries("C:\\Program Files\\Java\\jdk1.8.0_40\\bin\\keytool",
            "C:\\Users\\carl_000\\git\\resignator-repos-1\\resignator\\emptykeystore", "xxx");

    System.out.println("# entries=" + CollectionUtils.size(entries));
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    List<Dish> menu = Arrays.asList(new Dish("pork", false, 800, Dish.Type.MEAT),
            new Dish("beef", false, 700, Dish.Type.MEAT), new Dish("chicken", false, 400, Dish.Type.MEAT),
            new Dish("rice", true, 350, Dish.Type.OTHER), new Dish("pizza", true, 550, Dish.Type.OTHER),
            new Dish("prawns", false, 400, Dish.Type.FISH), new Dish("salmon", false, 450, Dish.Type.FISH));
    // map//from  ww  w  . j  a v  a 2  s . c  o  m
    List<String> dishNames = menu.stream().map(Dish::getName).collect(Collectors.toList());
    System.out.println(dishNames);

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    List<Person> persons = Arrays.asList(new Person("Max", 18), new Person("Peter", 23),
            new Person("Pamela", 23), new Person("David", 12));

    Collector<Person, StringJoiner, String> personNameCollector = Collector.of(() -> new StringJoiner(" | "), // supplier
            (j, p) -> j.add(p.name.toUpperCase()), // accumulator
            (j1, j2) -> j1.merge(j2), // combiner
            StringJoiner::toString); // finisher

    String names = persons.stream().collect(personNameCollector);

    System.out.println(names);//from w ww .ja va  2 s.  c  o  m
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    List<Dish> menu = Arrays.asList(new Dish("pork", false, 800, Dish.Type.MEAT),
            new Dish("beef", false, 700, Dish.Type.MEAT), new Dish("chicken", false, 400, Dish.Type.MEAT),
            new Dish("rice", true, 350, Dish.Type.OTHER), new Dish("pizza", true, 550, Dish.Type.OTHER),
            new Dish("prawns", false, 400, Dish.Type.FISH), new Dish("salmon", false, 450, Dish.Type.FISH));
    // Skipping elements
    List<Dish> dishesSkip2 = menu.stream().filter(d -> d.getCalories() > 300).skip(2)
            .collect(Collectors.toList());

    dishesSkip2.forEach(System.out::println);

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    List<Dish> menu = Arrays.asList(new Dish("pork", false, 800, Dish.Type.MEAT),
            new Dish("beef", false, 700, Dish.Type.MEAT), new Dish("chicken", false, 400, Dish.Type.MEAT),
            new Dish("rice", true, 350, Dish.Type.OTHER), new Dish("pizza", true, 550, Dish.Type.OTHER),
            new Dish("prawns", false, 400, Dish.Type.FISH), new Dish("salmon", false, 450, Dish.Type.FISH));
    // Truncating a stream
    List<Dish> dishesLimit3 = menu.stream().filter(d -> d.getCalories() > 300).limit(3)
            .collect(Collectors.toList());

    dishesLimit3.forEach(System.out::println);

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    List<Dish> menu = Arrays.asList(new Dish("pork", false, 800, Dish.Type.MEAT),
            new Dish("beef", false, 700, Dish.Type.MEAT), new Dish("chicken", false, 400, Dish.Type.MEAT),
            new Dish("rice", true, 350, Dish.Type.OTHER), new Dish("pizza", true, 550, Dish.Type.OTHER),
            new Dish("prawns", false, 400, Dish.Type.FISH), new Dish("salmon", false, 450, Dish.Type.FISH));
    // Filtering with predicate
    List<Dish> vegetarianMenu = menu.stream().filter(Dish::isVegetarian).collect(Collectors.toList());

    vegetarianMenu.forEach(System.out::println);

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    List<Dish> menu = Arrays.asList(new Dish("pork", false, 800, Dish.Type.MEAT),
            new Dish("beef", false, 700, Dish.Type.MEAT), new Dish("chicken", false, 400, Dish.Type.MEAT),
            new Dish("rice", true, 350, Dish.Type.OTHER), new Dish("pizza", true, 550, Dish.Type.OTHER),
            new Dish("prawns", false, 400, Dish.Type.FISH), new Dish("salmon", false, 450, Dish.Type.FISH));
    // Filtering with predicate
    Optional<Dish> vegetarianMenu = menu.stream().filter(Dish::isVegetarian).findAny();

    vegetarianMenu.ifPresent(d -> System.out.println(d.getName()));

}