Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain of Map method references

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.

like image 556
mossaab Avatar asked Nov 14 '14 00:11

mossaab


People also ask

What is the method reference?

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.

WHAT ARE method references in Java 8?

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.


1 Answers

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)) 
like image 93
Misha Avatar answered Sep 24 '22 10:09

Misha