Create a Stream
There are several ways to create a stream in Java 8. Here are the main methods:
- From a Collection:
List<String> list = Arrays.asList("a", "b", "c"); Stream<String> stream = list.stream();
- From an array:
String[] array = {"a", "b", "c"}; Stream<String> stream = Arrays.stream(array);
- Using Stream.of():
Stream<String> stream = Stream.of("a", "b", "c");
- Using Stream.generate():
Stream<Double> randomNumbers = Stream.generate(Math::random);
- Using Stream.iterate():
Stream<Integer> evenNumbers = Stream.iterate(0, n -> n + 2);
- From a file (lines):
Stream<String> lines = Files.lines(Paths.get("file.txt"));
- From a string:
IntStream streamOfChars = "abc".chars();
- Using Stream.builder():
Stream<String> stream = Stream.<String>builder().add("a").add("b").add("c").build();
- From a range of integers:
IntStream range = IntStream.range(1, 5); // 1, 2, 3, 4 IntStream rangeClosed = IntStream.rangeClosed(1, 5); // 1, 2, 3, 4, 5
- Parallel streams from collections:
Stream<String> parallelStream = list.parallelStream();
These are the most common ways to create streams in Java 8. Each method has its use cases depending on the data source and the specific requirements of our application.