Java 的 Func 和 Action 等价物

2022-08-31 10:43:49

Java的FuncAction的等价物是什么?

我的意思是,与其自己写这个:

public interface Func<TInput, TResult>
{
    TResult call(TInput target) throws Exception;
}
public interface Action<T>
{
    void call(T target) throws Exception;
}

答案 1

在Java 8中,等效的分别是java.util.function.Function<T,R>java.util.function.Consumer<T>接口。类似地,java.util.function.Predicate<T> 等效于 。如其他地方所述,这些是接口而不是委托。System.Predicate<T>

相关方面:我目前严重依赖以下实用程序类来执行类似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;
  }
}

与这里介绍的类似 LINQ 的方法不同,它不是惰性的,而是在将结果集合返回给调用方之前完全遍历源集合。尽管如此,我发现它们对于纯粹的语法目的很有用,如果有必要,可以变得懒惰。鉴于System.Linq.Enumerable.Where<TSource>System.Linq.Enumerable.Select<TSource, TResult>

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

答案 2

可调用接口类似于 Func。

可运行接口类似于操作。

通常,Java 使用匿名内部类作为 C# 委托的替代品。例如,这是添加代码以响应GUI中的按钮按下的方式:

button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) { 
          ...//code that reacts to the action... 
      }
});

推荐