Example usage for java.util.stream Stream concat

List of usage examples for java.util.stream Stream concat

Introduction

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

Prototype

public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) 

Source Link

Document

Creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.

Usage

From source file:Main.java

public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
    List<Integer> numbers1 = Arrays.asList(1, 2, 3, 4, 5);

    Stream<Integer> s = Stream.concat(numbers.stream(), numbers1.stream());

    System.out.println(s.count());
}

From source file:org.lightjason.trafficsimulation.CMain.java

/**
 * main method/*  www.j  a va2  s  .c  om*/
 *
 * @param p_args arguments
 * @throws Exception on URI syntax error
 */
public static void main(final String[] p_args) throws Exception {
    // --- define CLI options ------------------------------------------------------------------------------------------------------------------------------

    final Options l_clioptions = new Options();
    l_clioptions.addOption("help", false, "shows this information");
    l_clioptions.addOption("generateconfig", false, "generate default configuration");
    l_clioptions.addOption("config", true,
            "path to configuration directory (default: <user home>/.asimov/configuration.yaml)");

    final CommandLine l_cli;
    try {
        l_cli = new DefaultParser().parse(l_clioptions, p_args);
    } catch (final Exception l_exception) {
        System.err.println("command-line arguments parsing error");
        System.exit(-1);
        return;
    }

    // --- process CLI arguments and initialize configuration ----------------------------------------------------------------------------------------------

    if (l_cli.hasOption("help")) {
        new HelpFormatter().printHelp(
                new java.io.File(CMain.class.getProtectionDomain().getCodeSource().getLocation().getPath())
                        .getName(),
                l_clioptions);
        return;
    }

    if (l_cli.hasOption("generateconfig")) {
        System.out.println(MessageFormat.format("default configuration was created under [{0}]",
                CConfiguration.createdefault()));
        return;
    }

    // load configuration and start the http server (if possible)
    CConfiguration.INSTANCE.loadfile(l_cli.getOptionValue("config", ""));

    // initialize server
    CHTTPServer.initialize();

    // --- add test agents -----------------------------------------------------------
    final Map<String, IAgent<?>> l_agents = new ConcurrentHashMap<>();

    final Set<IAction> l_actions = Stream.concat(Stream.of(new CSend(l_agents), new CBroadcast(l_agents)),
            org.lightjason.agentspeak.common.CCommon.actionsFromPackage()).collect(Collectors.toSet());

    final IEnvironment l_env = EObjectFactory.ENVIRONMENT
            .generate(CMain.class.getResourceAsStream("asl/environment.asl"), l_actions.stream())
            .generatesingle(25, 25, 2.5, new CJPSPlus()).<IEnvironment>raw();

    l_env.beliefbase().stream().forEach(System.out::println);
    l_env.call().call();

    EObjectFactory.PEDESTRIAN.generate(

            CMain.class.getResourceAsStream("asl/pedestrian.asl"),

            l_actions.stream(),

            l_env

    ).generatemultiple(3, new DenseDoubleMatrix1D(2)).forEach(i -> {
    });
    // -------------------------------------------------------------------------------

    // execute server
    CHTTPServer.execute();
}

From source file:org.lightjason.examples.pokemon.CMain.java

/**
 * initialization//from w  w w . j a v  a2s  .  c  om
 *
 * @param p_args CLI arguments
 * @throws IOException on configuration file reading
 * @throws URISyntaxException on URI sytax definition
 */
public static void main(final String[] p_args) throws IOException, URISyntaxException {
    // --- define CLI options ------------------------------------------------------------------------------------------------------------------------------

    final Options l_clioptions = new Options();
    l_clioptions.addOption("help", false, "shows this information");
    l_clioptions.addOption("generate", true, "generates an example configuration within the current directory");
    l_clioptions.addOption("configuration", true, "defines the simulation configuration");

    final CommandLine l_cli;
    try {
        l_cli = new DefaultParser().parse(l_clioptions, p_args);
    } catch (final Exception l_exception) {
        System.err.println("command-line arguments parsing error");
        System.exit(-1);
        return;
    }

    // --- process CLI arguments and initialize configuration ----------------------------------------------------------------------------------------------

    if (l_cli.hasOption("help")) {
        new HelpFormatter().printHelp(
                new java.io.File(CMain.class.getProtectionDomain().getCodeSource().getLocation().getPath())
                        .getName(),
                l_clioptions);
        System.exit(0);
        return;
    }

    if (l_cli.hasOption("generate")) {
        System.exit(Stream.of("agent.asl", "configuration.yaml").parallel().map(i -> {
            try {
                FileUtils.copyURLToFile(CCommon.getResourceURL(CCommon.PACKAGEPATH + i),
                        Paths.get(l_cli.getOptionValue("generate", "."), i).normalize().toFile());
                return true;
            } catch (final IOException | URISyntaxException l_exception) {
                System.err.println(l_exception);
                return false;
            }
        }).allMatch(i -> i) ? 0 : -1);
        return;
    }

    // --- read configuration and initialize simulation ui -------------------------------------------------------------------------------------------------

    CConfiguration.INSTANCE.load(l_cli.hasOption("configuration") ? l_cli.getOptionValue("configuration")
            : CCommon.PACKAGEPATH + "configuration.yaml");

    // force-exit must be disabled for avoid error exiting
    final LwjglApplicationConfiguration l_config = new LwjglApplicationConfiguration();

    l_config.forceExit = false;
    l_config.width = CConfiguration.INSTANCE.windowweight();
    l_config.height = CConfiguration.INSTANCE.windowheight();

    // open window
    LOGGER.info(MessageFormat.format("open window with size [{0}x{1}]", l_config.width, l_config.height));
    final CScreen l_screen = new CScreen(
            Stream.concat(CConfiguration.INSTANCE.staticelements().parallelStream(),
                    CConfiguration.INSTANCE.agents().parallelStream()).collect(Collectors.toList()),
            CConfiguration.INSTANCE.environment(), CConfiguration.INSTANCE.screenshot());
    new LwjglApplication(l_screen, l_config);
    CMain.execute(l_screen);
}

From source file:com.ikanow.aleph2.analytics.spark.assets.SparkJsInterpreterTopology.java

public static void main(String[] args)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {

    final SetOnce<IBucketLogger> bucket_logger = new SetOnce<>();
    final SetOnce<String> job_name = new SetOnce<>(); // (the string we'll use in logging activities)
    try {//from   www.j  a v  a  2  s. c  om
        final Tuple2<IAnalyticsContext, Optional<ProcessingTestSpecBean>> aleph2_tuple = SparkTechnologyUtils
                .initializeAleph2(args);
        final IAnalyticsContext context = aleph2_tuple._1();
        final Optional<ProcessingTestSpecBean> test_spec = aleph2_tuple._2();

        bucket_logger.set(context.getLogger(context.getBucket()));
        job_name.set(context.getJob().map(j -> j.name()).orElse("no_name"));

        // Optional: make really really sure it exists after the specified timeout
        SparkTechnologyUtils.registerTestTimeout(test_spec, () -> {
            System.exit(0);
        });

        final SparkTopologyConfigBean config = BeanTemplateUtils
                .from(context.getJob().map(job -> job.config()).orElse(Collections.emptyMap()),
                        SparkTopologyConfigBean.class)
                .get();

        final String js_script = Optional.ofNullable(config.script()).orElse("");

        //INFO:
        System.out.println("Starting " + job_name.get());

        SparkConf spark_context = new SparkConf().setAppName(job_name.get());

        test_spec.ifPresent(spec -> System.out
                .println("OPTIONS: test_spec = " + BeanTemplateUtils.toJson(spec).toString()));

        try (final JavaSparkContext jsc = new JavaSparkContext(spark_context)) {

            final Multimap<String, JavaPairRDD<Object, Tuple2<Long, IBatchRecord>>> inputs = SparkTechnologyUtils
                    .buildBatchSparkInputs(context, test_spec, jsc, Collections.emptySet());
            final JavaPairRDD<Object, Tuple2<Long, IBatchRecord>> all_inputs = inputs.values().stream()
                    .reduce((acc1, acc2) -> acc1.union(acc2)).orElse(null);

            // Load globals:
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");
            engine.put("_a2_global_context", context);
            engine.put("_a2_global_bucket", context.getBucket().get());
            engine.put("_a2_global_job", context.getJob().get());
            engine.put("_a2_global_config",
                    BeanTemplateUtils.configureMapper(Optional.empty()).convertValue(config, JsonNode.class));
            engine.put("_a2_global_mapper", BeanTemplateUtils.configureMapper(Optional.empty()));
            //TODO (until bucket logger is serializable, don't allow anywhere)
            //engine.put("_a2_bucket_logger", bucket_logger.optional().orElse(null));
            engine.put("_a2_enrichment_name", job_name.get());
            engine.put("_a2_spark_inputs", inputs);
            engine.put("_a2_spark_inputs_all", all_inputs);
            engine.put("_a2_spark_context", jsc);

            Stream.concat(config.uploaded_lang_files().stream(),
                    Stream.of("aleph2_sparkjs_globals_before.js", ""))
                    .flatMap(Lambdas.flatWrap_i(import_path -> {
                        try {
                            if (import_path.equals("")) { // also import the user script just before here
                                return js_script;
                            } else
                                return IOUtils.toString(SparkJsInterpreterTopology.class.getClassLoader()
                                        .getResourceAsStream(import_path), "UTF-8");
                        } catch (Throwable e) {
                            bucket_logger.optional()
                                    .ifPresent(l -> l.log(Level.ERROR,
                                            ErrorUtils.lazyBuildMessage(false,
                                                    () -> SparkJsInterpreterTopology.class.getSimpleName(),
                                                    () -> job_name.get() + ".main", () -> null,
                                                    () -> ErrorUtils.get(
                                                            "Error initializing stage {0} (script {1}): {2}",
                                                            job_name.get(), import_path, e.getMessage()),
                                                    () -> ImmutableMap.<String, Object>of("full_error",
                                                            ErrorUtils.getLongForm("{0}", e)))));

                            System.out.println(ErrorUtils.getLongForm("onStageInitialize: {0}", e));
                            throw e; // ignored
                        }
                    })).forEach(Lambdas.wrap_consumer_i(script -> {
                        try {
                            engine.eval(script);
                        } catch (Throwable e) {
                            bucket_logger.optional()
                                    .ifPresent(l -> l.log(Level.ERROR,
                                            ErrorUtils.lazyBuildMessage(false,
                                                    () -> SparkJsInterpreterTopology.class.getSimpleName(),
                                                    () -> job_name.get() + ".main", () -> null,
                                                    () -> ErrorUtils.get(
                                                            "Error initializing stage {0} (main script): {1}",
                                                            job_name.get(), e.getMessage()),
                                                    () -> ImmutableMap.<String, Object>of("full_error",
                                                            ErrorUtils.getLongForm("{0}", e)))));

                            System.out.println(ErrorUtils.getLongForm("onStageInitialize: {0}", e));
                            throw e; // ignored
                        }
                    }));
            ;

            jsc.stop();

            //INFO:
            System.out.println("Finished " + job_name.get());
        }
    } catch (Throwable t) {
        System.out.println(ErrorUtils.getLongForm("ERROR: {0}", t));

        bucket_logger.optional().ifPresent(l -> l.log(Level.ERROR, ErrorUtils.lazyBuildMessage(false,
                () -> SparkJsInterpreterTopology.class.getSimpleName()
                        + job_name.optional().map(j -> "." + j).orElse(""),
                () -> job_name.optional().orElse("global") + ".main", () -> null,
                () -> ErrorUtils.get("Error on batch in job {0}: {1}",
                        job_name.optional().orElse("global") + ".main", t.getMessage()),
                () -> ImmutableMap.<String, Object>of("full_error", ErrorUtils.getLongForm("{0}", t)))));
    }
}

From source file:Main.java

/**
 * Joins 2 collections into one list.//from  w  w  w  .  j  av  a2  s .c  o  m
 *
 * @param a Some collection
 * @param b Some other collection
 * @param <T> The type of the elements
 *
 * @return A List that contains all the elements of both collections.
 */
public static <T> List<T> join(Collection<? extends T> a, Collection<? extends T> b) {
    return Stream.concat(a.stream(), b.stream()).collect(Collectors.toList());
}

From source file:org.apache.james.mailbox.backup.FlagsExtraField.java

private static String serializeFlags(Flags flags) {
    return Stream
            .concat(StreamUtils.ofNullable(flags.getSystemFlags()).map(FlagsExtraField::systemFlagToString),
                    StreamUtils.ofNullable(flags.getUserFlags()))
            .collect(Collectors.joining("%"));
}

From source file:com.github.robozonky.internal.util.ToStringBuilder.java

private ToStringBuilder(final Object o, final String... excludeFields) {
    final String[] fieldExclusions = Stream.concat(Stream.of("password"), Arrays.stream(excludeFields))
            .distinct().toArray(String[]::new);
    this.builder = new CustomReflectionToStringBuilder(o).setExcludeFieldNames(fieldExclusions);
}

From source file:net.sf.jabref.model.entry.CustomEntryType.java

public CustomEntryType(String name, List<String> required, List<String> primaryOptional,
        List<String> secondaryOptional) {
    this.name = EntryUtil.capitalizeFirst(name);
    this.primaryOptional = primaryOptional;
    this.required = required;
    this.optional = Stream.concat(primaryOptional.stream(), secondaryOptional.stream())
            .collect(Collectors.toList());
}

From source file:org.apache.james.blob.cassandra.utils.DataChunker.java

public Stream<Pair<Integer, ByteBuffer>> chunk(byte[] data, int chunkSize) {
    Preconditions.checkNotNull(data);//w w w.  jav  a 2s  .  c o  m
    Preconditions.checkArgument(chunkSize > 0, "ChunkSize can not be negative");

    int size = data.length;
    int fullChunkCount = size / chunkSize;

    return Stream.concat(
            IntStream.range(0, fullChunkCount)
                    .mapToObj(i -> Pair.of(i, ByteBuffer.wrap(data, i * chunkSize, chunkSize))),
            lastChunk(data, chunkSize * fullChunkCount, fullChunkCount));
}

From source file:com.intuit.quickbase.MergeStatService.java

public void retrieveCountryPopulationList() {

    DBStatService dbStatService = new DBStatService();
    List<Pair<String, Integer>> dbList = dbStatService.GetCountryPopulations();

    ConcreteStatService conStatService = new ConcreteStatService();
    List<Pair<String, Integer>> apiList = conStatService.GetCountryPopulations();

    //Use of Predicate Interface
    Predicate<Pair<String, Integer>> pred = (pair) -> pair != null;

    if (apiList != null) {
        // Converting the keys of each element in the API list to lowercase
        List<Pair<String, Integer>> modifiedAPIList = apiList.stream().filter(pred)
                .map(p -> new ImmutablePair<String, Integer>(p.getKey().toLowerCase(), p.getValue()))
                .collect(Collectors.toList());
        //modifiedAPIList.forEach(pair -> System.out.println("key: " + pair.getLeft() + ": value: " + pair.getRight()));                      

        if (dbList != null) {
            // Merge two list and remove duplicates
            Collection<Pair<String, Integer>> result = Stream.concat(dbList.stream(), modifiedAPIList.stream())
                    .filter(pred)//from  www. j  av  a 2  s  .  c  om
                    .collect(Collectors.toMap(Pair::getLeft, p -> p, (p, q) -> p, LinkedHashMap::new)).values();

            // Need to Convert collection to List
            List<Pair<String, Integer>> merge = new ArrayList<>(result);
            merge.forEach(pair -> System.out.println("key: " + pair.getKey() + ": value: " + pair.getValue()));

        } else {
            System.out.println("Country list retrieved form database is empty");
        }
    } else {
        System.out.println("Country list retrieved form API is empty");
    }

    //            if(apiList != null) {
    //                Iterator itr = apiList.iterator();
    //                for(Pair<String, Integer> pair : apiList){                    
    //                    //System.out.println("key: " + pair.getLeft() + ": value: " + pair.getRight());
    //                }                
    //            }    

}