3 ms·
Code blocks are just lambdas though? It's pretty much mainstream these days, even Java and C++ have them. // java equivalent int numberOfAuthors = arr.
by ajuc 5y ago
Code blocks are just lambdas though? It's pretty much mainstream these days, even Java and C++ have them.
// java equivalent
int numberOfAuthors = arr.stream().map(BlogPost::getAuthor).distinct().collect(Collectors.toList()).size();
I happen to think for loops are usually a better choice in languages like Java, but the option is there.
EDIT: actually there's a better way, no need to create a list just to count its elements:
int numberOfAuthors = arr.stream().map(BlogPost::getAuthor).distinct().collect(Collectors.counting());
- setpatchaddress 5y agoNote how much more concise and yet readable the equivalent Ruby is.
- ajuc 5y agoIf you want to play code golf you can do static imports and write this: int numberOfAuthors = arr.stream().map(getAuthor).distinct().collect(counting()); You still save a few parentheses and one method call in Ruby (.compact vs .stream() and .collect()) and the method names are shorter. Mostly it's a matter of static vs dynamic typing and naming conventions, not a consequence of Ruby code blocks. And is it worth shortening at this point? BTW I know uniq is a thing in unix, but I hate this naming decision.
- cma 5y agoBlocks are a bit different, they can do things like return from the enclosing method. Ultimately I don't think it is worth the complexity and code coloring it adds.