I want to replace lambda expression by method reference in the below example :
public class Example {
public static void main(String[] args) {
List<String> words = Arrays.asList("toto.", "titi.", "other");
//lambda expression in the filter (predicate)
words.stream().filter(s -> s.endsWith(".")).forEach(System.out::println);
}
}
I want to write a something like this :
words.stream().filter(s::endsWith(".")).forEach(System.out::println);
is it possible to transform any lambda expression to method reference.
You can use
selectWith()
from Eclipse Collections.selectWith()
takes a Predicate2 which takes 2 parameters instead of aPredicate
. The second parameter toselectWith()
gets passed as the second parameter to thePredicate2
every time it's called, once per item in the iterable.By default Eclipse Collections is eager, if you want to iterate lazily then you can use
asLazy()
If you can't change from
List
:Eclipse Collections' RichIterable has several other *With methods which work well with method references, including
rejectWith()
,partitionWith()
,detechWith()
,anySatisfyWith()
,allSatisfyWith()
,noneSatisfyWith()
,collectWith()
Note: I am a contributor to Eclipse Collections.
There is no way “to transform any lambda expression to method reference”, but you can implement a factory for a particular target type, if this serves recurring needs:
with this, you can write
but actually, there’s no advantage. Technically, a lambda expression does exactly what you want, there’s the minimum necessary argument transformation code, expressed as the lambda expression’s body, compiled into a synthetic method and a method reference to that synthetic code. The syntax
s -> s.endsWith(".")
also is already the smallest syntax possible to express that intent. I doubt that you can find a smaller construct that would still be compatible with the rest of the Java programming language.