What you are using isn't lambda. Lambda looks like (arguments) -> action
. What you have in A::getName
is method reference, but additional ::length
is not part of its syntax.
Instead of A::getName::length
you can use lambda like a -> a.getName().length()
.
But your code has yet another problem. Code
list_a.stream()
.max(Comparator.comparingInt(A::getName::length));
is handling streams of A
and max
method called on Stream<A>
will result in Optional<A>
not int
. It is Optional
because there is a chance that list_a
can be empty which means that there will be no valid result.
If you want to get OptionalInt you would need to map
Stream<A>
to Stream<String>
and then map
it to Stream of int
s first. Then you can call its max()
method and get:
OptionalInt maxOpt = list_a.stream()
.map(A::getName)
.mapToInt(String::length)
.max();
When you already have OptionalInt
you can use it to check if value there isPresent()
and get it via getAsInt()
. You can also use orElse(defaultValueIfEmpty)
like
int max = maxOpt.orElse(-1); //will return value held by maxOpt, or -1 if there is no value