In this tutorial, we will see “How to convert a List to a Stream in Java 8?” And, also we will learn how to filter the stream using Predicate.
Convert a List to a Stream & filter the stream in Java 8 with example...!!! Click To Tweet
Example 1. Convert a List to a Stream
To convert list to a stream, we are going to use List.stream() which returns a sequential Stream with the collection as its source.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import java.util.Arrays; import java.util.List; import java.util.stream.Stream; class Convert_List_To_Stream_Java8 { public static void main(String args[]) { // Create a list of string List <String> listObj = Arrays.asList("Techndeck", "Technology Blog", "For Programmers & Entrepreneurs"); // Print the List System.out.println("List: \n" + listObj); // Convert List to stream Stream <String> stream = listObj.stream(); // Print the Stream System.out.println("\nStream: \n" + Arrays.toString(stream.toArray())); } } |
Output:
1 2 3 4 5 | List: [Techndeck, Technology Blog, For Programmers & Entrepreneurs] Stream: [Techndeck, Technology Blog, For Programmers & Entrepreneurs] |
Example 2. Filter a Stream using Predicate
Predicate is a function interface part of the java.util.function package. It’s main purpose is to be used as a assignment target for a lambda expression. To filter the stream, we are going to use filter(predicate expression) to build a stream of elements which matches the predicate expression.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import java.util.Arrays; import java.util.List; import java.util.function.Predicate; class Filter_Stream_Using_Predicate_Java8 { public static void main(String args[]) { // Create a list of string List <String> listObj = Arrays.asList("Techndeck", "Technology Blog", "For Programmers & Entrepreneurs"); // Print the List System.out.println("List: \n" + listObj); // Create the predicate which build with items starting with character 'T' Predicate <String> predicateObj = s -> s.startsWith("T"); System.out.println("\nStream from List whose items starting with 'T': "); // Convert List to stream with predicate filter and print it listObj.stream() .filter(predicateObj) .forEach(System.out::println); } } |
Output:
1 2 3 4 5 6 | List: [Techndeck, Technology Blog, For Programmers & Entrepreneurs] Stream from List whose items starting with 'T': Techndeck Technology Blog |
Convert a List to a Stream & filter the stream in Java 8 with example...!!! Click To Tweet
Do you like this Post? – then check my other helpful posts: