1

I have the following code:

boolean allApproved = traverse(root)
                .map(element -> element.getAttribute(LisecConstants.ATTRIBUTE_APPROVED))
                .filter(Objects::nonNull)
                .map(Boolean::parseBoolean)
                .allMatch(x -> x);

where some elements get traversed, then mapped for an "approved" attribute and in the end I want to know if all elements are approved.

Sometimes I stumble upon the case where I use a lambda expression like "x -> x" like here. Although this expression is probably shorter than any short form, is there an expression used with the double colon operator? I think this makes the code more readable and more consistent with the rest of the code.

I am aware that I simply could rewrite the code a bit different and probably dodge this case here, but let's keep it simple:

Is there an alternative expression for x -> x?

psmears
  • 26,070
  • 4
  • 40
  • 48
BAERUS
  • 4,009
  • 3
  • 24
  • 39
  • 2
    [Function.identity()](https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html#identity--) – Eran Apr 18 '16 at 11:05
  • This is also a duplicate http://stackoverflow.com/q/32233524/1743880 – Tunaki Apr 18 '16 at 11:09
  • 1
    `.map(Boolean::parseBoolean).allMatch(x -> x);` => `.allMatch(Boolean::parseBoolean);` - doesn't this work (can't test now). – Antti Haapala -- Слава Україні Apr 18 '16 at 11:10
  • Ok, nice to know about `Function.identity()`. Though please notice that it won't work just out of the box in that specific case as the all/anymatch needs an Predicate and not a function. – BAERUS Apr 18 '16 at 11:35
  • `traverse(root) .map(element -> element.getAttribute( ATTRIBUTE_APPROVED)) .allMatch(Boolean::parseBoolean);` saves you from both, `map` and `filter` as it will handle `null` as well. Or even shorter: `traverse(root) .allMatch(element -> Boolean.parseBoolean( element.getAttribute( ATTRIBUTE_APPROVED)))`… – Holger Apr 18 '16 at 12:27

0 Answers0