4 ms·
>Java 8 has a nice stream and lambda syntax. You could write code like this: final List<String> filtered = list.stream() .filter(s -> s.startsWith("s"))
by tsotha 11y ago
>Java 8 has a nice stream and lambda syntax. You could write code like this:
final List<String> filtered = list.stream()
.filter(s -> s.startsWith("s"))
.map(s -> s.toUpperCase())
.collect(Collectors.toList());
>Instead of this:
final List<String> filtered = new ArrayList<>();
for (String str : list) {
if (str.startsWith("s") {
filtered.add(str.toUpperCase());
}
}
>This allows you to write more fluent code, which is more readable.
I don't agree. The second snipped is far more readable. This seems like an effort to use lambdas just to be using lambdas.
Not only that, but the non-lambda version is far easier to maintain. When you get exceptions in code that has the form
this().that().theOther()
it's generally not obvious where the problem is.
- deleted 11y ago[deleted]
- ap22213 11y agoA matter of personal taste, but I greatly prefer the lambda style (though I wish the example had the .stream() on the following line). I have been coding Java (and C-style) languages for a really long time. And, I still have some cognitive delay when traversing multiple indented scopes. Not a long delay, but long enough to be slightly annoying. With the lambda style, I can quickly glance down the text column to see what's going on. Stream -> Map -> Filter -> Collect. After using lambdas enough, one starts to subconsciously cull the stream() and collect() calls. So, when I look at it, I really see Map -> Filter. But what really, really annoys me is that exception handling can't be applied to the whole stream processing statement. This leads to code that looks like: collection .stream() .map(o -> { try { return o.oToC(); } catch(Exception e) { // handle } return new C(); }) .reduce((c1, c2) -> { try { return c1.combine(c2); } catch(Exception e) { // handle } return c1; }); For that, I have had to write a bunch of helper functions that wrap and throw the exceptions.