Video in progress
In what ways can you create a stream?
stream() from a collection, Arrays.stream() from an array, Stream.of() from values, IntStream.range() for a range of numbers, Stream.iterate() and Stream.generate() for an infinite stream, and Files.lines() from a file.
📖 Answer
Stream<String> s1 = List.of("a", "b").stream();
IntStream s2 = Arrays.stream(new int[]{3, 1, 2});
Stream<String> s3 = Stream.of("x", "y", "z");
IntStream s4 = IntStream.range(0, 10); // 0..9
IntStream s5 = IntStream.rangeClosed(1, 10); // 1..10
Stream<Integer> evens = Stream.iterate(0, n -> n + 2).limit(5); // 0,2,4,6,8
Stream<Integer> upTo = Stream.iterate(1, n -> n < 100, n -> n * 2); // Java 9+, with a condition
Stream<UUID> ids = Stream.generate(UUID::randomUUID).limit(3);
Stream<String> words = Pattern.compile("\\s+").splitAsStream("bir ikki uch");
IntStream chars = "salom".chars();
Files.lines(path) keeps the file open, so use it inside try-with-resources.
Map itself has no stream(). You start from map.entrySet().stream(), map.keySet().stream() or map.values().stream().
Be careful with Stream.of(array): if you pass an int[], you get a Stream<int[]> with a single element. For a primitive array use Arrays.stream.
Sign up to mark studied questions and save your progress.