假设我在Java 8中有以下功能接口:
interface Action<T, U> {
U execute(T t);
}
Run Code Online (Sandbox Code Playgroud)
在某些情况下,我需要一个没有参数或返回类型的操作.所以我写这样的东西:
Action<Void, Void> a = () -> { System.out.println("Do nothing!"); };
Run Code Online (Sandbox Code Playgroud)
但是,它给了我编译错误,我需要把它写成
Action<Void, Void> a = (Void v) -> { System.out.println("Do nothing!"); return null;};
Run Code Online (Sandbox Code Playgroud)
这很难看.有没有办法摆脱Void类型参数?
Google Guava有一个始终返回true的谓词.Java 8有类似的东西Predicate吗?我知道我可以使用(foo)->{return true;},但我想要预制的东西,类似于Collections.emptySet().
什么是一个方法的Java 8功能接口什么都不带,什么都不返回?
即,相当于Action带void返回类型的C#参数?
我需要有一个Runnable没有做任何事情的函数接口的lambda表达式.我曾经有过一种方法
private void doNothing(){
//Do nothing
}
Run Code Online (Sandbox Code Playgroud)
然后使用this::doNothing.但我发现了一个更短的方法来做到这一点.
我只是注意到Consumer没有identity()像有那样的方法java.util.function.Function。
是的,这只是一个可以放入东西的洞,但至少可以完全清楚地知道我不仅仅是在括号中遗漏了一些代码。
以这个人为的例子为例:
public void applyConsumerIfExists(String key, String param) {
Map<String, Consumer<String>> consumers = new HashMap<>();
consumers.put("a", MyClass::myConsumer);
// I can create my own, but that's no fun :(
Consumer<String> identity = input -> {};
consumers.getOrDefault(key, identity).accept(param);
// DOESN'T WORK, since identity() doesn't exist on Consumer
consumers.getOrDefault(key, Consumer.identity()).accept(param);
}
Run Code Online (Sandbox Code Playgroud)
问题
为什么没有Consumer方法identity呢?