I am trying to join a list of names:
List<String> names;
names = books.stream()
.map( b -> b.getName() )
.filter( n -> ( (n != null) && (!n.isEmpty()) ) )
.collect(Collectors.joining(", "));
This does not compile saying:
incompatible types. inference variable R has incompatible bounds
So after some research, it seems that there is something I misunderstood. I thought that .map( b -> b.getName() ) returned/changed the type to a String, and it seems something is wrong there. If I use .map(Book::getName) instead, I still get an error, but I probably don't fully understand the difference.
However, this does not complain:
List<String> names;
names = books.stream()
.map( b -> b.getName() )
.map( Book::getName )
.filter( n -> ( (n != null) && (!n.isEmpty()) ) )
.collect(Collectors.joining(", "));
Can someone explain me why? Some didactic explanation about differences between .map( b -> b.getName() ) and .map(Book::getName) are appreciated too, since I think I didn't get it right.
.filter( n -> ( (n != null) && (!n.isEmpty()) ) )improves the readability compared to a straight-forward.filter(n -> n!=null && !n.isEmpty())?&&and||is not intuitively to answer, so placing braces for clarity, even where unnecessary, has a point. But for a sole&&operator, there is no way of misinterpreting the expression. Further, there is another outer bracket pair unrelated to the logical expression. Since you didn’t writeb -> (b.getName())either, having an outer pair at the other expression, is inconsistent..map(b -> b.getName()).map(Book::getName)works but only.map(b -> b.getName())doesn't? Sobooksis actually not a collection ofBook? Sob.getName()returns aBook? Probably that is also the reason, why it's not complaining.