0 votes
in JAVA by
What is a Stream? How to create Streams in Java?

1 Answer

0 votes
by
The stream represents a sequence of objects from a source such as a collection, which supports aggregate operations.

You can use Stream to filter, collect, print, and convert from one data structure to another, etc.

Stream does not store elements. It simply conveys elements from a source such as a data structure, an array, or an I/O channel, through a pipeline of computational operations.

Stream is functional in nature. Operations performed on a stream do not modify its source. For example, filtering a Stream obtained from a collection produces a new Stream without the filtered elements, rather than removing elements from the source collection.

Here are the examples to create a Stream using different sources.

Creating Empty Stream

The empty() method should be used in case of the creation of an empty stream:

Stream<String> stream = Stream.empty();

stream.forEach(System.out::println);

Creating Stream from From Collections

A stream can be created of any type of Collection (Collection, List, Set):

        Collection<String> collection = Arrays.asList("JAVA", "J2EE", "Spring", "Hibernate");

        Stream<String> stream2 = collection.stream();

        stream2.forEach(System.out::println);

        List<String> list = Arrays.asList("JAVA", "J2EE", "Spring", "Hibernate");

        Stream<String> stream3 = list.stream();

        stream3.forEach(System.out::println);

        Set<String> set = new HashSet<>(list);

        Stream<String> stream4 = set.stream();

        stream4.forEach(System.out::println);

Creating Stream object from Arrays

Array can be a source of a Stream or Array can be created from the existing array or of a part of an array:

        // Array can also be a source of a Stream

        Stream<String> streamOfArray = Stream.of("a", "b", "c");

        streamOfArray.forEach(System.out::println);

Creating Stream object from String using chars() method

We can also use String as a source for creating a stream with the help of the chars() method of the String class.

IntStream streamOfChars = "abc".chars();
...