×

iFour Logo

A Guide on Java Stream API

Kapil Panchal - June 20, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
A Guide on Java Stream API

What is Java Stream API?


Java Stream API was added as a new feature in Java 8 – java.util.stream – which contains classes for processing sequences of elements. This package consists of classes, interfaces, and enum to allow functional-style operations on the elements. Simply by importing java.util.stream package in your file, you can make use of Stream.

A stream provides a set/collection of elements of a particular type in a sequential manner. A stream gets/computes elements on demand. It never stores the elements.

A stream is not a data structure, it just takes Collections, Arrays, or I/O resources as an input source. Stream supports aggregate operations namely filter, map, limit, reduce, find, match, and many more to use. Stream operations do the iterations internally over the source elements provided.

Streams don’t change the data structure which is officially there but only provide the result as per the predefined/ inbuilt methods.

Each intermediate operation is executed and returns a stream as a result, hence various intermediate operations can be pipelined.

Transform your operations with our Custom API integration services.


Different Methods for Streams


 

Intermediate methods

map: The map method is used to returns a stream consisting of the results of applying the given function to the elements of this stream.

Example:
    List no = Arrays.asList(2,3,4,5);
    List square_no = number.stream().
    map(x->x*x).collect(Collectors.toList());
    
         
    List uris = new ArrayList<>();
           uris.add("C:\\My.txt"); 
    Stream stream = uris.stream().map(uri -> Paths.get(uri));
    
    
    
                    

filter: The filter method is used to select elements as per the implied argument. So we can get our desired output only.

Example:
    List names = Arrays.asList("yash","sarthak","amit");
    List result = names.stream().
    filter(s->s.startsWith("s")).collect(Collectors.toList());
    
    
    ArrayList list = new ArrayList<>();
     list.add("Monday");
    list.add("Tuesday");
     list.add("Wednesday");
     list.add("Change");
     list.add("factory");
     list.add("Tomorrow");
     list.add("Italy"); 
    list.add("Yesterday");
     list.add("Thursday");
    
    Stream stream = list.stream().filter(element -> element.contains("d"));
    
    
                    

sorted: The sorted method is definitely used for the sorting of the stream.

Example:
    List names = Arrays.asList("Reflection","Collection","Stream");
    List result = names.stream().sorted().collect(Collectors.toList());
                    

Terminal methods

collect: The collect method is used to return the result of the intermediate operations performed on the stream.

Example:
    List number = Arrays.asList(2,3,4,5,3);
    Set square = number.stream().map(x->x*x).collect(Collectors.toSet());
                    

forEach: The forEach method is used to iterate through an element that all are inside the stream.

Example:
    List number = Arrays.asList(2,3,4,5);
    number.stream().map(x->x*x).forEach(y->System.out.println(y));
                    

reduce: Stream API allows reducing a sequence of elements to some value according to a specified function with the help of the reduce () method of the type Stream. This method takes two parameters: first – start value, second – an accumulator function. This method takes a Binary Operator as a parameter.

Example:
    List number = Arrays.asList(2,3,4,5);
    int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);
    
    List integers = Arrays.asList(3, 1, 2); Integer reduced = integers.stream().reduce(13, (a, b) -> a - b);
    
                    

Match: Stream API gives a very useful and important set of instruments to validate elements of a sequence according to some predicate in the argument. To do this, one of the following methods can be used: anyMatch(), allMatch(), noneMatch(). We can understand their uses by their names.

Example:
    boolean isValid = list.stream().anyMatch(element -> element.contains("s"));  
    // if there is ‘s’ then will show true or else false.
    boolean isValidOne = list.stream().allMatch(element -> element.contains("t")); 
    // if all elements have ‘t’ then true or else false.
    boolean isValidTwo = list.stream().noneMatch(element -> element.contains("a"));
    // if none of the element has ‘a’ then true or else false.
                    

Extra Examples:


For a simple condition comparison
    import java.util.*;  
    class Product{  
        int id;  
        String name;  
        float price;  
        public Product(int id, String name, float price) {  
            this.id = id;  
            this.name = name;  
            this.price = price;  
        }  
    }  
    public class JavaStreamExample {  
        public static void main(String[] args) {  
            List productsList = new ArrayList();  
            //Adding Products in the productlist 
            productsList.add(new Product(1," redmi note 10",25000f ));  
            productsList.add(new Product(2," asus roug",30000f));  
            productsList.add(new Product(3," samsung note 10 lite ",28000f ));  
            productsList.add(new Product(4, “ Sony Experia 3",28000f));  
            productsList.add(new Product(5," Apple iphone 12 pro max ",90000f ));  
            List productPriceList = new ArrayList();  
            for(Product product: productsList){  
      
                if(product.price<30000){  
                    productPriceList.add(product.price);     
                }  
            }  
            System.out.println(productPriceList);   // display data  
        }  
    }  
    
    
                    
Output

codeoutput1


For iteration
    import java.util.stream.*;  
    public class JavaStreamExample {  
        public static void main(String[] args){  
            Stream.iterate(1, element->element+1)  
            .filter(element -> element%5==0)  
            .limit(5)  
            .forEach(System.out::println);  
        }  
    }  
                   
Output

codeoutput2


To find sum
    import java.util.*;  
    import java.util.stream.Collectors;  
    class Product{  
        int id;  
        String name;  
        float price;  
        public Product(int id, String name, float price) {  
            this.id = id;  
            this.name = name;  
            this.price = price;  
        }  
    }  
    public class JavaStreamExample {  
        public static void main(String[] args) {  
            List productsList = new ArrayList();  
            //Adding Products  in the list
            productsList.add(new Product(1," HP spector x360 Laptop",25000f ));  
            productsList.add(new Product(2," Dell inspiron Laptop",30000f ));  
            productsList.add(new Product(3," Lenovo legion Laptop",28000f ));  
            productsList.add(new Product(4," Sony Laptop",28000f));  
            productsList.add(new Product(5," Apple mac book pro Laptop",90000f ));  
            // Using Collectors's method to sum the prices.  
            double totalPrice3 = productsList.stream()  
                            .collect(Collectors.summingDouble(product -> product.price ));  
            System.out.println(totalPrice3);  
              
        }  
    }  
    
    
                   
Output

codeoutput3


For count() method
    import java.util.*;  
    class Product{  
        int id;  
        String name;  
        float price;  
        public Product(int id, String name, float price) {  
            this.id = id;  
            this.name = name;  
            this.price = price;  
        }  
    }  
    public class JavaStreamExample {  
        public static void main(String[] args) {  
            List productsList = new ArrayList();  
            //Adding Products in the list
            productsList.add(new Product(1," HP Laptop",25000f ));  
            productsList.add(new Product(2," Dell xps Laptop",30000f ));  
            productsList.add(new Product(3," Lenevo yoga book Laptop",28000f ));  
            productsList.add(new Product(4," Sony Laptop",28000f));  
            productsList.add(new Product(5," Apple mac book Laptop ",90000f ));  
            // count number of products based on the filter  
            long count = productsList.stream()  
                        .filter(product -> product.price<30000)  //filter of data
                        .count();  
            System.out.println(count);  
        }  
    }  
    
    
                   

Searching for Reliable JAVA Development Company? Your Search ends here.


Output

codeoutput4


For filtering data
    import java.util.*;  
    import java.util.stream.Collectors;  
    class Product{  
        int id;  
        String name;  
        float price;  
        public Product(int id, String name, float price) {  
            this.id = id;  
            this.name = name;  
            this.price = price;  
        }  
    }  
    public class JavaStreamExample {  
        public static void main(String[] args) {  
            List productsList = new ArrayList();  
            //Adding Products in the list 
            productsList.add(new Product(1," HP Laptop",25000f ));  
            productsList.add(new Product(2," Dell Laptop",30000f ));  
            productsList.add(new Product(3," Lenevo Laptop",28000f ));  
            productsList.add(new Product(4," Sony Laptop",28000f ));  
            productsList.add(new Product(5," Apple Laptop",90000f ));  
            List productPriceList2 = productsList.stream()  
                                         .filter(p -> p.price > 30000)// filtering data  
                                         .map(p->p.price)        // fetching price  
                                         .collect(Collectors.toList()); // collecting as list  
            System.out.println(productPriceList2);  
        }  
    }  
    
    
Output

codeoutput5

Conclusion


In this blog, we have learned Java Stream API with significant examples. So as mentioned earlier this is a very important feature added in Java 8.

A Guide on Java Stream API Table of Content 1. What is Java Stream API? 2. Different Methods for Streams 2.1. Intermediate methods 2.2. Terminal methods 3. Extra Examples 4. Conclusion What is Java Stream API? Java Stream API was added as a new feature in Java 8 – java.util.stream – which contains classes for processing sequences of elements. This package consists of classes, interfaces, and enum to allow functional-style operations on the elements. Simply by importing java.util.stream package in your file, you can make use of Stream. A stream provides a set/collection of elements of a particular type in a sequential manner. A stream gets/computes elements on demand. It never stores the elements. A stream is not a data structure, it just takes Collections, Arrays, or I/O resources as an input source. Stream supports aggregate operations namely filter, map, limit, reduce, find, match, and many more to use. Stream operations do the iterations internally over the source elements provided. Streams don’t change the data structure which is officially there but only provide the result as per the predefined/ inbuilt methods. Each intermediate operation is executed and returns a stream as a result, hence various intermediate operations can be pipelined. Transform your operations with our Custom API integration services. See here Different Methods for Streams   Intermediate methods map: The map method is used to returns a stream consisting of the results of applying the given function to the elements of this stream. Example: List no = Arrays.asList(2,3,4,5); List square_no = number.stream(). map(x->x*x).collect(Collectors.toList()); List uris = new ArrayList(); uris.add("C:\\My.txt"); Stream stream = uris.stream().map(uri -> Paths.get(uri)); filter: The filter method is used to select elements as per the implied argument. So we can get our desired output only. Example: List names = Arrays.asList("yash","sarthak","amit"); List result = names.stream(). filter(s->s.startsWith("s")).collect(Collectors.toList()); ArrayList list = new ArrayList(); list.add("Monday"); list.add("Tuesday"); list.add("Wednesday"); list.add("Change"); list.add("factory"); list.add("Tomorrow"); list.add("Italy"); list.add("Yesterday"); list.add("Thursday"); Stream stream = list.stream().filter(element -> element.contains("d")); sorted: The sorted method is definitely used for the sorting of the stream. Example: List names = Arrays.asList("Reflection","Collection","Stream"); List result = names.stream().sorted().collect(Collectors.toList()); Read More: Top 5 Trending Javascript Framework 2018 Terminal methods collect: The collect method is used to return the result of the intermediate operations performed on the stream. Example: List number = Arrays.asList(2,3,4,5,3); Set square = number.stream().map(x->x*x).collect(Collectors.toSet()); forEach: The forEach method is used to iterate through an element that all are inside the stream. Example: List number = Arrays.asList(2,3,4,5); number.stream().map(x->x*x).forEach(y->System.out.println(y)); reduce: Stream API allows reducing a sequence of elements to some value according to a specified function with the help of the reduce () method of the type Stream. This method takes two parameters: first – start value, second – an accumulator function. This method takes a Binary Operator as a parameter. Example: List number = Arrays.asList(2,3,4,5); int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i); List integers = Arrays.asList(3, 1, 2); Integer reduced = integers.stream().reduce(13, (a, b) -> a - b); Match: Stream API gives a very useful and important set of instruments to validate elements of a sequence according to some predicate in the argument. To do this, one of the following methods can be used: anyMatch(), allMatch(), noneMatch(). We can understand their uses by their names. Example: boolean isValid = list.stream().anyMatch(element -> element.contains("s")); // if there is ‘s’ then will show true or else false. boolean isValidOne = list.stream().allMatch(element -> element.contains("t")); // if all elements have ‘t’ then true or else false. boolean isValidTwo = list.stream().noneMatch(element -> element.contains("a")); // if none of the element has ‘a’ then true or else false. Extra Examples: For a simple condition comparison import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products in the productlist productsList.add(new Product(1," redmi note 10",25000f )); productsList.add(new Product(2," asus roug",30000f)); productsList.add(new Product(3," samsung note 10 lite ",28000f )); productsList.add(new Product(4, “ Sony Experia 3",28000f)); productsList.add(new Product(5," Apple iphone 12 pro max ",90000f )); List productPriceList = new ArrayList(); for(Product product: productsList){ if(product.price<30000){ productPriceList.add(product.price); } } System.out.println(productPriceList); // display data } } Output For iteration import java.util.stream.*; public class JavaStreamExample { public static void main(String[] args){ Stream.iterate(1, element->element+1) .filter(element -> element%5==0) .limit(5) .forEach(System.out::println); } } Output To find sum import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products in the list productsList.add(new Product(1," HP spector x360 Laptop",25000f )); productsList.add(new Product(2," Dell inspiron Laptop",30000f )); productsList.add(new Product(3," Lenovo legion Laptop",28000f )); productsList.add(new Product(4," Sony Laptop",28000f)); productsList.add(new Product(5," Apple mac book pro Laptop",90000f )); // Using Collectors's method to sum the prices. double totalPrice3 = productsList.stream() .collect(Collectors.summingDouble(product -> product.price )); System.out.println(totalPrice3); } } Output For count() method import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products in the list productsList.add(new Product(1," HP Laptop",25000f )); productsList.add(new Product(2," Dell xps Laptop",30000f )); productsList.add(new Product(3," Lenevo yoga book Laptop",28000f )); productsList.add(new Product(4," Sony Laptop",28000f)); productsList.add(new Product(5," Apple mac book Laptop ",90000f )); // count number of products based on the filter long count = productsList.stream() .filter(product -> product.price<30000) //filter of data .count(); System.out.println(count); } } Searching for Reliable JAVA Development Company? Your Search ends here. See here Output For filtering data import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products in the list productsList.add(new Product(1," HP Laptop",25000f )); productsList.add(new Product(2," Dell Laptop",30000f )); productsList.add(new Product(3," Lenevo Laptop",28000f )); productsList.add(new Product(4," Sony Laptop",28000f )); productsList.add(new Product(5," Apple Laptop",90000f )); List productPriceList2 = productsList.stream() .filter(p -> p.price > 30000)// filtering data .map(p->p.price) // fetching price .collect(Collectors.toList()); // collecting as list System.out.println(productPriceList2); } } Output Conclusion In this blog, we have learned Java Stream API with significant examples. So as mentioned earlier this is a very important feature added in Java 8.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
How Spatial Data Analysis Improves Healthcare
How Spatial Data Analysis Improves Healthcare

Do you know when geospatial analysis took traction in healthcare? It was when John Snow, a London-based physician, used it to analyze the spread of cholera, which ultimately proved...

4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical
4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical

One interesting aspect you truly love about Power BI, as a CTO, is how it lets you step back and see the bigger picture of your business. Isn’t it? Without getting bogged down in minute...

Power Apps Integration Challenges: Expert Insights & Solutions
Power Apps Integration Challenges: Expert Insights & Solutions

Power Apps Integration Challenges: Insights from 11 Experts Microsoft Power Apps has caught great hype in recent days. Why? because it helps you build apps 50% faster, saves 250+...