Logo

dev-resources.site

for different kinds of informations.

Simplifying Data Processing with Java Stream API

Published at
5/21/2024
Categories
java
javastream
dataprocessing
coding
Author
tharindufdo
Author
11 person written this
tharindufdo
open
Simplifying Data Processing with Java Stream API

Java Stream API, introduced in Java 8, revolutionized how developers process data collections. This functional-style approach makes code more readable. In this blog, weโ€™ll dive into a real-world example to demonstrate the power and flexibility of the Java Stream API.

Before we get into the example, letโ€™s briefly look at the core concepts of the Stream API:

  • Streams: Sequences of elements supporting sequential and parallel operations.

  • Intermediate Operations: Transform streams into another stream (e.g., map, filter).

  • Terminal Operations: Produce a result or side effect (e.g., collect, forEach).

Real-World Scenario: E-commerce Order Processing

Step 1: Setting Up the Data Models

public class Customer {
    private Long id;
    private String name;
    private String email;

//constructor,getters and setter, tostring
}

public class Order {
    private Long id;
    private LocalDate date;
    private Customer customer;
    private List<Product> products;
    private BigDecimal total;

//constructor,getters and setter, tostring
}

public class Product {
    private Long id;
    private String name;
    private BigDecimal price;

//constructor,getters and setter, tostring
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Letโ€™s create some sample orders to work with.


public class SampleData {
    public static List<Order> getOrders() {
        Customer customer1 = new Customer(1L, "Alice Smith", "[email protected]");
        Customer customer2 = new Customer(2L, "Bob Johnson", "[email protected]");

        Product product1 = new Product(1L, "Laptop", new BigDecimal("1200.00"));
        Product product2 = new Product(2L, "Smartphone", new BigDecimal("800.00"));
        Product product3 = new Product(3L, "Tablet", new BigDecimal("600.00"));

        Order order1 = new Order(1L, LocalDate.now().minusDays(2), customer1, Arrays.asList(product1, product3), new BigDecimal("1800.00"));
        Order order2 = new Order(2L, LocalDate.now().minusDays(1), customer2, Arrays.asList(product2), new BigDecimal("800.00"));
        Order order3 = new Order(3L, LocalDate.now(), customer1, Arrays.asList(product1, product2, product3), new BigDecimal("2600.00"));

        return Arrays.asList(order1, order2, order3);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Letโ€™s perform various operations on this data using the Stream API.

public class StreamExamples {

    //this method will return the total revenue of orders
    public static BigDecimal totalRevenue(List<Order> orders){

        BigDecimal totalRevenue = orders.stream()
                .map(Order::getTotal)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        return totalRevenue;
    }

    //this method will return the list of all products that were sold
    public static List<Product> getAllProductsSold(List<Order> orders){

        List<Product> productsSold = orders.stream()
                .flatMap(order -> order.getProducts().stream())
                .distinct()
                .toList();

        return productsSold;

    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

The examples above showcase just a few ways you can use the Stream API to handle common tasks in an e-commerce application. As you continue to explore, youโ€™ll find even more opportunities to simplify and enhance your Java code with streams.

References

https://www.baeldung.com/java-8-streams

https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html

https://www.geeksforgeeks.org/stream-in-java/

GitHub : https://github.com/tharindu1998/StreamAPIBlogExample

dataprocessing Article's
30 articles in total
Favicon
What is Real-Time Data Processing?
Favicon
Apache Spark vs. Apache Flink: A Comparison of the Data Processing Duo
Favicon
Data Manipulation with Strings and Arrays in Bash
Favicon
How to Choose the best Automated Data Processing Equipment
Favicon
Simplifying Data Processing with Java Stream API
Favicon
All About Database Sharding and Improving Scalability.
Favicon
Understanding Apache Spark and Hadoop Jobs
Favicon
How to Choose the Right Data Processing Service Provider: A Comprehensive Guide
Favicon
Real-Time Data Scrubbing Before Storing In A Data Warehouse
Favicon
The Modern Data Stack - An essential guide
Favicon
Beginner's guide to Apache Flink
Favicon
Kubernetes for Big Data Processing.
Favicon
How to do question answering from a PDF
Favicon
Standardizing the Data Using StandardScaler in ML
Favicon
Introducing Memphis Functions
Favicon
Elements of Event Driven Architecture(EDA)
Favicon
What is data collection for machine learning?
Favicon
Event-Driven Architecture with Serverless Functions โ€“ Part 1
Favicon
Simplify Data Cleansing with YAML Configurations
Favicon
How to deduplicate scraped data
Favicon
Data Processing with Elixir (Part 2)
Favicon
From Transactions to Analytics: Exploring the World of OLTP and OLAP.
Favicon
Part 3: Transforming MongoDB CDC Event Messages
Favicon
kafka: distributed task queue
Favicon
Getting started with Apache Flink: A guide to stream processing
Favicon
Apache Flink vs Apache Spark: A detailed comparison for data processing
Favicon
Memphis is now GA!
Favicon
Real-Time Data Processing using AWS
Favicon
What Is DPA and Why Is It a Must in Software Development Outsourcing?
Favicon
Customer Data Pipeline And Data Processing: Types, Importance, And Benefits

Featured ones: