多个lambda方法引用 [英] Multiple lambda method references

查看:567
本文介绍了多个lambda方法引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以链接/连接lambda表达式中的元素,如下所示:

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;
});


推荐答案

通过功能接口的默认方法可以进行链接。但是问题在于,当您返回合成表达式的右侧时,推理引擎没有足够的信息来确定左侧是相同的功能接口。

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));

或先将其分配给变量:

  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
}

这篇关于多个lambda方法引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆