Menu

Java 8 Streams vs Loops: Cleaner Code, Same Complexity?
📰

Java 8 Streams vs Loops: Cleaner Code, Same Complexity?

DEV Community: java·ayesha azhar·about 13 hours ago
#plz3eH8s
#devtojava#devto#dev#stream#order
Reading 0:00
15s threshold

Most Java developers have written hundreds of for loops that filter, transform, and group data. They work, but they bury the intent of the code under boilerplate. Java 8’s Stream API lets you describe what you want instead of how to get it. But how do streams compare with loops in performance? Let’s look at both readability and time complexity.

* From Loop to Stream

*

Suppose we need the total revenue of completed orders over $100, grouped by customer. The classic approach:

Map < String , Double > revenueByCustomer = new HashMap <> ( ) ; for ( Order order : orders ) { if ( order . getStatus ( ) == Status . COMPLETED && order . getTotal ( ) > 100 ) { revenueByCustomer . merge ( order . getCustomerName ( ) , order . getTotal ( ) , Double :: sum ) ; } }

Enter fullscreen mode

Exit fullscreen mode

And the stream version:

Map < String , Double > revenueByCustomer = orders . stream ( ) . filter ( o -> o . getStatus ( ) == Status . COMPLETED ) . filter ( o -> o . getTotal ( ) > 100 ) . collect ( Collectors .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.