I'm working with Twitter4J. But the question I'm asking is more general. I want to access the user id of a given tweet. Currently, I have the following two options:
//Option 1 stream.map(status -> status.getUser().getId()) .forEach(System.out::println); //Option 2: stream.map(Status::getUser) .map(User:getId) .forEach(System.out::println);
I don't like the lambda expression in the first option, nor being forced to call two maps
in the second one. Is there a way to make a chain of method references? I know that Status::getUser::getId
does not work, but am wondering if there is an alternative.
Method references are a special type of lambda expressions. They're often used to create simple lambda expressions by referencing existing methods. There are four kinds of method references: Static methods. Instance methods of particular objects.
Java provides a new feature called method reference in Java 8. Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.
Nope, these are the two ways of doing it. Anything else would end up being only less clear.
But, since you asked, here are some options.
static<T,U,R> Function<T,R> chain( Function<? super T, ? extends U> f1, Function<? super U, ? extends R> f2) { return t -> f2.apply(f1.apply(t)); } stream.map(chain(Status::getUser, User::getId))
Or
static<T,R> Function<T,R> func(Function<T,R> f) { return f; } stream.map(func(Status::getUser).andThen(User::getId))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With