我的意思是,不要自己写这个:
public interface Func<TInput, TResult>
{
TResult call(TInput target) throws Exception;
}
public interface Action<T>
{
void call(T target) throws Exception;
}
最佳答案
在 Java 8 中,等价于 java.util.function.Function<T, R>
和 java.util.function.Consumer<T>
接口(interface)分别。同样, java.util.function.Predicate<T>
相当于 System.Predicate<T>
.如其他地方所述,这些是接口(interface)而不是委托(delegate)。
除此之外:我目前非常依赖以下实用程序类来执行类似 LINQ 的扩展方法:
abstract class IterableUtil {
public static <T> Iterable<T> where(Iterable<T> items, Predicate<T> predicate) {
ArrayList<T> result = new ArrayList<T>();
for (T item : items) {
if (predicate.test(item)) {
result.add(item);
}
}
return result;
}
public static <T, R> Iterable<R> select(Iterable<T> items, Function<T, R> func) {
ArrayList<R> result = new ArrayList<R>();
for (T item : items) {
result.add(func.apply(item));
}
return result;
}
}
不同于 System.Linq.Enumerable.Where<TSource>
和 System.Linq.Enumerable.Select<TSource, TResult>
我在这里介绍的类似 LINQ 的方法不是惰性的,并且在将结果集合返回给调用者之前会完全遍历源集合。尽管如此,我发现它们对于纯粹的句法目的很有用,如果必要的话可以变得懒惰。给定
class Widget {
public String name() { /* ... */ }
}
可以执行以下操作:
List<Widget> widgets = /* ... */;
Iterable<Widget> filteredWidgets = IterableUtil.where(widgets, w -> w.name().startsWith("some-prefix"));
我更喜欢以下:
List<Widget> widgets = /* ... */;
List<Widget> filteredWidgets = new ArrayList<Widget>();
for (Widget w : widgets) {
if (w.name().startsWith("some-prefix")) {
filteredWidgets.add(w);
}
}
关于Java 的 Func 和 Action 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1184418/