Ways of creating finite streams:
- collection.stream() call on a Collection to get a stream of all the elements contained in that collection.
List<Integer> list = List.of(2, 54, 567, 78, 23); Stream<Integer> streamIntegers = list.stream();
This gives a Stream of elements contained in the list. We can use this stream() method with every collection, but there is no direct way to create a stream from a map because the map has pairs of key-value unlike lists and other collections that have data arranged linearly.
There is no stream() method in Map. Though We have methods like entrySet() and keySet() and values() on a map, we can leverage them to create streams.
Map<Integer,String> map = Map.of(1, "one", 2, "two", 3, "Three", 4, "four"); //to get stream of entries Stream<Entry<Integer,String>> entries = map.entrySet().stream(); //to get stream of values Stream<String> values = map.values().stream(); //to get stream of keys Stream<Integer> keys = map.keySet().stream();
- Stream.of() call with the number of elements. This returns a sequential ordered stream whose elements are the specified values.
Stream<String> streamStrings = Stream.of("Hey!", "Happy", "ThanksGiving");
We can create Streams holding any type of objects using Streams.of() method.
- Arrays.stream(array) is used to create a stream of array elements. Unlike stream() method of Collection, Arrays.stream() is a static method, so we pass the array as argument.
Integer[] arr1 = { 6, 7, 9, 23, 56 }; Stream<Integer> str1 = Arrays.stream(arr1);
Note: If the array is primitive array then Arrays.stream() will return primitive stream.
- Builder<T> builder() method of Stream returns a builder for the stream. Elements can get added to the builder by using add() method. Later to get the stream build() can be invoked, which returns Stream.
Stream.Builder<String> builder = Stream.builder(); builder.add("a"); builder.add("b"); //invoke build() when we need the stream Stream<String> stream = builder.build();
This approach of creating stream is more flexible than using the of() method, as we can add elements in stream whenever – wherever we want!
These were the approaches to create finite streams.