Sobes.tech
Senior

How can you create a Stream?

sobes.tech AI

Answer from AI

In Java, a Stream can be created in several ways:

  1. From a collection using the stream() or parallelStream() method:
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();
  1. From an array using Arrays.stream():
int[] numbers = {1, 2, 3};
IntStream stream = Arrays.stream(numbers);
  1. Using the static method Stream.of():
Stream<String> stream = Stream.of("x", "y", "z");
  1. Creating infinite streams using Stream.generate() or Stream.iterate():
Stream<Double> randoms = Stream.generate(Math::random);
Stream<Integer> integers = Stream.iterate(0, n -> n + 1);
  1. From a BufferedReader to read lines from a file:
try (Stream<String> lines = Files.lines(Paths.get("file.txt"))) {
    // processing
}

Thus, a Stream is created from a data source or generator, allowing the application of functional operations for data processing.