r/learnjava • • Aug 01 '19

Tips to Become a Better Java Developer

67 Upvotes

8 comments sorted by

6

u/[deleted] Aug 01 '19

Anyone knows some common real world situations for streams? While learning I almost never even have the thought that a Stream could help me right now.

9

u/Hioneqpls Aug 01 '19

Heres a stream that I wrote for work yesterday.

BigDecimal sumOfAmount =
        transactions.stream()
            .map(CommonGLTransaction::getAmount)
            .reduce(BigDecimal.ZERO, BigDecimal::add);    

Whats happening is that I have a set of transaction objects that I wanna sum up and use. To do this with loops, counters would be a bore.

2

u/[deleted] Aug 01 '19

Thank you for the example!

3

u/[deleted] Aug 01 '19

There's nothing you can do with streams that can't be done with imperative style programming, such as normal loops. However, once you know the stream API, code written with streams is easier to read and reason about IMO. It's the whole declarative vs imperative paradigm, where declarative code tells you more about what it does and abstracts away how it is doing it.

2

u/[deleted] Aug 01 '19

Yeah, I understand that part by now but my head simply never goes for the stream instead of the loop. That's why I'm looking for real world examples to get some triggers.

2

u/nidrach Aug 01 '19

you got a list of elements and want to extract a sum of a certain attribute of elements that fulfill certain criteria. What would it cost to buy all books of a certain author for example. You could make a loop and iterate over that and write an if clause and then add that all to a variable. Or you could stream, filter, map and reduce. Want a list of those elements simply stream, filter and collect.

You can do all those things with loops and ifs and so on but streams make it more readable IMHO.

1

u/zaeemr Nov 26 '19

!remindme 1 year

1

u/RemindMeBot Nov 26 '19

I will be messaging you in 11 months on 2020-11-26 17:32:58 UTC to remind you of this link

CLICK THIS LINK to send a PM to also be reminded and to reduce spam.

Parent commenter can delete this message to hide from others.


InfoCustomYour RemindersFeedback