Javatpoint Logo
Javatpoint Logo

Program to Convert List to Stream in Java

A list is a type of data structure in programming that represents an ordered collection of elements. It allows storing and accessing elements sequentially and supports adding, removing, and retrieving elements. Lists are commonly used for organizing and manipulating data in various programming languages.

Streams are a feature in programming languages like Java that provide a concise and powerful way to process data sequences. They allow for functional-style operations like filtering, mapping, and reducing collections, enabling efficient and expressive manipulation of data in a declarative manner.

Approach: List.stream() method

The List.stream() method is a method of the List class in Java. It gives back a stream of the list's items. A data sequence that may be processed one element at a time is known as a stream. The stream() method can perform various operations on the elements of the list, such as filtering, mapping, and reducing.

Algorithm:

  1. Start the main method.
  2. Create a List of strings and initialize it with the elements "Hello" and "World".
  3. Convert the list to a Stream using the stream() method.
  4. Print each stream element using the forEach() method and the System.out::println method reference.
  5. End the main method.

Implementation:

Filename: ConvertListToStream.java

Output:

Hello
World

Approach: Filter Stream using a Predicate

A predicate is a method that takes an element of a stream as an input and returns a boolean value. Using a predicate as an input, the filter() method on the Stream interface creates a new stream that only contains components from the old stream that the predicate evaluates to true.

Algorithm:

  1. Create a list of strings.
  2. Convert the list to a stream.
  3. Create a predicate that tests if a string starts with the letter "b".
  4. Filter the stream using the predicate.
  5. Print the filtered elements.

Implementation:

Filename: ConvertListToStream2

Output:

banana






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA