3 ms·
"Stream-based code is certainly not something you can read off the cuff." List<Integer> transactionsIds = transactions.stream()
by jimbokun 10y ago
"Stream-based code is certainly not something you can read off the cuff."
List<Integer> transactionsIds =
transactions.stream()
.filter(t -> t.getType() == Transaction.GROCERY)
.sorted(comparing(Transaction::getValue).reversed())
.map(Transaction::getId)
.collect(toList());
I honestly think most programmers fluent in Java 7 programming, can guess this is finding "grocery" type transactions, sorting by "value" transaction property in descending order, extracting the transaction ids, and returning the result as a list. ("map" could be confusing, as this usage is borrowed from functional programming.)
May take a while to learn the performance and memory usage characteristics, and how to correctly write code in this style, but I'm not buying that it is difficult to "read off the cuff."
- douche 10y agoIf you're a .NET programmer, we've been doing that kind of stuff with LINQ for years; it's all over the place. The only patterns that I still like to keep as old-style loops are constructs that ReSharper transforms into hairy-looking Aggregate() expressions
- amirouche 10y agoIsn't the point of stream API a) to be able to iterate over infinite set of values b) to fiddle with the rate of "async" object generation? I'm not sure I understand the difference between `compose' and stream APIs.
- pyre 10y ago> ("map" could be confusing, as this usage is borrowed from functional programming.) On the other hand, both Python and Perl have 'map' as a built-in function. There has been spillage out of functional programming for a while.
- lenkite 10y agoErr..yes, Java 8's filter, sort, map and collect are the most basic stream operators and you are correct that even folks un-used to this style can determine an understanding. But in code that uses observable stream-based programming you nearly always use more complicated operators like flatMap, merge, skipWhile, takeUntil, combineLatest etc. Without spending time learning these operators and how streams work, one is always going to scratch one's head. (Unless you possess an FP background) Even in Java 8 plain streams, the Collector is a powerful paradigm for grouping operations with a large amount of variations and it takes (at-least it did for me) some involved time learning how to effectively leverage this in day to day code.
- dpritchett 10y agoHaven't touched Java in a decade and that is beautiful. I like Ruby's functional idioms and LINQ though.