Java 的 Func 和 Action 等价物

标签 java

Func 的 Java 等价物是什么?和 Action ?

我的意思是,不要自己写这个:

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/

相关文章:

java - 何时使用 session.replicate() 方法

java - Spring JPA : Query one column from the table without where clause

java - JUnit 不会在 Eclipse 中的断点处停止(使用 JDK 1.6.0.20)

java.lang.IllegalArgumentException : The given string value: { "In last 7 days" : 19 } cannot be transformed to Json object

java - 带有条件运算符(三元运算符)但不是 if else 的空指针异常

java - 如何为新登录用户创建新的 cookie Spring Security

java - 用可能的数字对字符串进行排序

java - Visual Studio Code 项目名称

java - 获取 GridLayout 中 JPanel 的位置/索引?

java - Kryonet 没有收到自定义类(class)