Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple lambda method references

It's possible to chain/concatenate what is done with elements in a lambda expression like this:

list.forEach(s -> {
        System.out.println(s.toLowerCase());
        System.out.println(s.toUpperCase());
});

Is there a way to do this also with method references? Something like this:

list.forEach({
    System.out::println(String::toLowerCase);
    System.out::println(String::toCase);
});

I know I could do this in four separate calls (which do also more, that is mutate the values):

list.replaceAll(String::toLowerCase);
list.forEach(System.out::println);
list.replaceAll(String::toUpperCase);
list.forEach(System.out::println);

I can't even do something easy like this:

list.forEach({
    System.out::println;
    System.out::println;
});
like image 472
dr0i Avatar asked Dec 06 '22 21:12

dr0i


1 Answers

chaining is possible through default methods of the functional interfaces. But the "problem" is that there that the inference engine does not have enough information to determine that the left hand side is the same functional interface when you're returning the right hand side of the compositing expression.

To provide that information you either have to cast the statement:

  List<String> l = Collections.emptyList();
  l.forEach(((Consumer<String>)System.out::println).andThen(System.out::println));

Or assign it to a variable first:

  Consumer<String> cons = System.out::println;
  Collections.<String>emptyList().forEach(cons.andThen(System.out::println));

Alternatively you could also write static helper methods that do what you want

Collections.<String>emptyList().forEach(combine(System.out::println, System.out::println));

static <T> Consumer<T> combine(Consumer<T>... consumers) {
    // exercise left to the reader
}
like image 142
the8472 Avatar answered Dec 19 '22 12:12

the8472