Senior
How can you create a Stream?
sobes.tech AI
Answer from AI
In Java, a Stream can be created in several ways:
- From a collection using the
stream()orparallelStream()method:
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();
- From an array using
Arrays.stream():
int[] numbers = {1, 2, 3};
IntStream stream = Arrays.stream(numbers);
- Using the static method
Stream.of():
Stream<String> stream = Stream.of("x", "y", "z");
- Creating infinite streams using
Stream.generate()orStream.iterate():
Stream<Double> randoms = Stream.generate(Math::random);
Stream<Integer> integers = Stream.iterate(0, n -> n + 1);
- From a
BufferedReaderto 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.