You can replace .filter(s -> aIDetailsDto.getResult().getIdNo().equals(s))
with .filter(aIDetailsDto.getResult().getIdNo()::equals)
, but you have to be aware of the semantic difference.
The lambda expression will evaluate the term aIDetailsDto.getResult().getIdNo()
every time the predicate function is evaluated, while the method reference will evaluate it when the Predicate
instance is created and capture the result value, to invoke equals
on the same object on each subsequent predicate evaluation. See also “What is the equivalent lambda expression for System.out::println
”.
If the expression aIDetailsDto.getResult().getIdNo()
is supposed to evaluate to the same result each time, it makes no difference and the method reference might be more efficient due to not evaluating it repeatedly.
Note also the alternative .filter(Predicate.isEqual(aIDetailsDto.getResult().getIdNo()))
, which will also evaluate the argument expression only once, but is the only variant handling the case that it evaluated to null
, by then accepting onlynull
elements (see Predicate.isEqual(…)
). However, when this value is supposed to never be null
, the throwing behavior of the other variants is preferable.