| by Arround The Web | No comments

Java Stream Examples

Java stream is a very useful feature of Java programming. It is not a data structure and it can’t store or modify the data like Java I/O streams. It is used to work on any data source such as an array, collection, I/O channel, etc. The data from one data structure can be retrieved, collected, or modified to another data structure using Java stream. The “java.util.stream” package is required to use the Java stream in the code. Different uses of Java stream in Java programs are shown in this tutorial.

Prerequisites:

  1. Install the latest version of OpenJDK with JRE.
  2. Install any useful editor to write and execute the Java code. You can check this tutorial to install the Eclipse editor.

Java Stream Examples

Creating streams from different data structures and filtering the stream data are shown in this part of the tutorial using multiple examples.

Example 1: Creating Stream Object from Arrays

Create a Java file with the following code to generate the stream with multiple values, with all elements of the array, and with a particular number of array values. The first stream is generated from three string values. The second stream is generated from an array of four values. The third stream is generated by cutting the first three elements of the array.

//Import necessary modules
import java.util.Arrays;
import java.util.stream.Stream;

public class JavaStreamExample {

    public static void main(String[] args) {
       
        //Declare a stream of an array
        Stream<String> stream1 = Stream.of("Object", "-Oriented ", "Programming");
        //Print all values of the stream
        stream1.forEach(System.out::print);
        //Add a new line
        System.out.println();

        //Declare an array of four string values
        String[] strarr = new String[] {"Learn", " Java"," Programming", " Language" };
        //Create a stream from an array of values
        Stream<String> stream2 = Arrays.stream(strarr);
        //Print all values of the stream
        stream2.forEach(System.out::print);
        //Add a new line
        System.out.println();

        //Create a stream with some elements of the array
        Stream<String> stream3 = Arrays.stream(strarr, 0, 3);
        stream3.forEach(System.out::print);
   }
}

The following output appears after executing the previous code. Three values of the first stream are printed in the first output. All values of the array are printed in the second output after converting them into the stream. The first three elements of the array are converted into the stream data and are printed in the third output.

Example 2: Creating Stream from Collections

Create a Java file with the following code to generate the stream from the “List”, “Set”, and “Collection” objects. A “List” object of three elements is defined in the code that is converted into the stream and is printed later. Next, a “Set” object is generated from the previously defined “List”. The “Set” is converted into the stream and is printed later. Next, a “Collection” object of three elements is generated and converted into the stream and is printed later.

//Import necessary modules
import java.util.stream.Stream;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.Collection;
import java.util.HashSet;

public class JavaStreamExample2 {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("Linux", "Hint", ".com");    
       
        //Create a stream from a list
        Stream<String> streamArray = list.stream();
        streamArray.forEach(System.out::print);
        System.out.println();
       
        //Create a stream from a Set
        Set<String> set = new HashSet<>(list);
        Stream<String> streamSet = set.stream();
        streamSet.forEach(System.out::print);
        System.out.println();

        //Create stream from a collection
        Collection<String> collection = Arrays.asList("Learn", "Java", "Stream");
        Stream<String> streamCollection = collection.stream();
        streamCollection.forEach(System.out::println);
   }
}

The following output appears after executing the previous code. Three values of the first and second streams are concatenated and printed in the first and second output for using the print() method. Each value of the third stream is printed with a newline in the third output for using the println() method.

Example 3: Filtering and Iterating the Collection

In the previous examples, a single list of data is used in the stream. But if you have to use multiple lists of data in the stream, you have to create a class to define the structure of the list data. Here, a class named “Employees” is declared with a constructor that contains four variables to store an employee id, name, post, and salary.

public class Employees {

   //Declare class variables
    public int id;
    public String name;
    public String post;
    public int salary;
   
    //Declare constructor
    public Employees(int a, String b, String c, int d)
    {
        id = a;
        name = b;
        post = c;
        salary = d;
    }

}

Create a Java file with the following code to generate the stream from the ArrayList. Next, the four records of the employee are added to the ArrayList. The list of the employees who have a salary of more than $60000 are filtered using the filter() method of the stream and is printed in the output.

//Import necessary modules
import java.util.List;
import java.util.*;

public class JavaStreamExample3 {

    public static void main(String[] args) {

        //Create an employee list based on the employee class
        List < Employees > empList = new ArrayList < Employees > ();
        //Insert 4 records into the list
        empList.add(new Employees (1, "Mir Sabbir", "Manager",60000));
        empList.add(new Employees (2, "Menhaz kazi", "Assistant Manager",50000));
        empList.add(new Employees (3, "Rupa Chowdhury", "CEO",100000));
        empList.add(new Employees (4, "Naznin Akter", "Accountant",75000));
       
        //
        System.out.println("Salary more than $60000");
        System.out.println("--------------------------");
       
        //Filter data using Java stream
        empList.stream().filter(Employees -> Employees.salary > 60000)
        .forEach(Employees -> System.out.println("Name:" + Employees.name + "\nSalary: $" + Employees.salary + "\n"));
    }
}

The following output appears after executing the previous code. Two records exist in the ArrayList that matches with the search criteria and are printed in the output. Here, the salary of “Rupa Chowdhury” and “Naznin Akter”  are $100000 and $75000 which are more than $60000.

Conclusion

The stream can be used for multiple purposes in Java programming. Some simple uses of the stream that are generated from the array and collection are shown in this tutorial to help the Java users to know the method of using the stream in their code.

Share Button

Source: linuxhint.com

Leave a Reply