Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

java - 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;
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...