Flat Preloader Icon

Java 8 Stream

In Java 8, the Stream API was introduced to facilitate functional-style operations on sequences of elements. Streams provide a way to process collections of data in a declarative way, enabling parallel processing and enhancing the overall performance of operations on large datasets. They also support a functional programming style and offer a range of useful methods for data processing.

Key Characteristics Of The Stream API In Java 8 include

Declarative:

  • Streams allow you to express the processing of data as a pipeline of operations, making the code more readable and concise.

Internal Iteration:

  • Streams handle iteration internally, simplifying the code and potentially enabling parallel processing of elements.

Lazy Evaluation:

  • Stream operations are evaluated only when necessary. This allows for efficient processing and minimizes unnecessary computation.

Pipelining:

  • You can combine multiple operations together to form a pipeline. Each operation in the pipeline is lazily executed on the elements as they pass through the pipeline.

Aggregate Operations:

  • Streams support various aggregate operations like filtering, mapping, sorting, and reducing elements. These operations are often more concise and readable compared to the traditional approach of using loops.
Here’s an example demonstrating the usage of the Stream API:
				
					import java.util.Arrays;
import java.util.List;

public class StreamExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList
        ("John", "Jane", "Adam", "Eva", 
        "Tom", "Emily");

        // Filtering names starting with "J" 
        and printing them
        names.stream()
             .filter(name -> name.startsWith("J"))
             .forEach(System.out::println);

        // Mapping names to uppercase 
        and printing them
        names.stream()
             .map(String::toUpperCase)
             .forEach(System.out::println);

        // Reducing the names to a single string
        String concatenatedNames = names.stream()
        .reduce("", (partialString, element) ->
        partialString + " " + element);
        System.out.println("Concatenated names:"
        + concatenatedNames);
    }
}

				
			
Streams provide a powerful way to process data in Java, enabling developers to write more efficient and expressive code for handling collections and arrays. They are particularly useful when working with large datasets and performing complex data manipulation operations.

Java Stream Interface Methods

Methods Description
boolean allMatch(Predicate predicate) It returns all elements of this stream which match the provided predicate. If the stream is empty then true is returned and the predicate is not evaluated.
boolean anyMatch(Predicate predicate) It returns any element of this stream that matches the provided predicate. If the stream is empty then false is returned and the predicate is not evaluated.
static Stream.Builder builder() It returns a builder for a Stream.
R collect(Collector collector) It performs a mutable reduction operation on the elements of this stream using a Collector. A Collector encapsulates the functions used as arguments to collect(Supplier, BiConsumer, BiConsumer), allowing for reuse of collection strategies and composition of collect operations such as multiple-level grouping or partitioning.
R collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner) It performs a mutable reduction operation on the elements of this stream. A mutable reduction is one in which the reduced value is a mutable result container, such as an ArrayList, and elements are incorporated by updating the state of the result rather than by replacing the result.
long count() It returns the count of elements in this stream. This is a special case of a reduction..

Method Reference In Stream

				
					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 int getId() {  
        return id;  
    }  
    public String getName() {  
        return name;  
    }  
    public float getPrice() {  
        return price;  
    }  
}  
  
public class JavaStreamExample {  
  
    public static void main(String[] args) {  
          
        List<Product> productsList = 
        new ArrayList<Product>();  
          
        //Adding Products  
        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<Float> productPriceList =   
                productsList.stream() 
.filter(p -> p.price > 30000)
// filtering data  
 .map(Product::getPrice)     
 // fetching price by referring getPrice method  
 .collect(Collectors.toList()); 
 // collecting as list  
        System.out.println(productPriceList);  
    }  
}