Sobes.tech
Middle

What are the ways to create a stream in Java?

sobes.tech AI

Answer from AI

There are several main ways to create streams:

  • From collections:
    • collection.stream(): creates a sequential stream.
    • collection.parallelStream(): creates a parallel stream.
  • From arrays:
    • Arrays.stream(array): creates a stream from the entire array.
    • Arrays.stream(array, startInclusive, endExclusive): creates a stream from a part of the array.
  • From individual elements:
    • Stream.of(element1, element2, ...): creates a stream from specified elements.
  • From primitive types using specialized classes:
    • IntStream.of(int1, int2, ...)
    • LongStream.of(long1, long2, ...)
    • DoubleStream.of(double1, double2, ...)
    • IntStream.range(startInclusive, endExclusive)
    • IntStream.rangeClosed(startInclusive, endInclusive)
    • LongStream.range(startInclusive, endExclusive)
    • LongStream.rangeClosed(startInclusive, endInclusive)
  • From generators:
    • Stream.generate(supplier): creates an infinite stream whose elements are generated using the provided Supplier.
    • Stream.iterate(seed, UnaryOperator): creates an infinite stream starting from the initial value (seed) and applying a unary operator to the previous element to get the next.
    • Stream.iterate(seed, Predicate, UnaryOperator): creates a stream similar to the previous, but with a stopping condition specified by a predicate.
  • From other sources:
    • BufferedReader.lines(): creates a stream from lines of a text file or another Reader.
    • Files.list(Path): creates a stream of paths in a directory.
    • Files.walk(Path): creates a stream of paths in a directory tree.
    • Random().ints(), Random().longs(), Random().doubles(): create streams of random primitive values.

Examples:

// From a collection
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Stream<String> nameStream = names.stream();
// From an array
int[] numbers = {1, 2, 3, 4, 5};
IntStream numberStream = Arrays.stream(numbers);
// From individual elements
Stream<String> greetingStream = Stream.of("Hello", "World");
// Using generate
Stream<Double> randomStream = Stream.generate(Math::random).limit(5);
// Using iterate
Stream<Integer> infiniteSequence = Stream.iterate(0, n -> n + 2);
Stream<Integer> finiteSequence = Stream.iterate(0, n -> n < 10, n -> n + 2);
What are the ways to create a stream in Java? — Java - sobes.tech