【问题标题】:Is there a underscore.js lib for java?java 是否有 underscore.js 库?
【发布时间】:2015-01-05 01:53:15
【问题描述】:

我经常使用javascript,发现underscorejs对于操作数组或对象等数据集非常方便。

我对 Java 很陌生,想知道是否有类似的 Java 库?

【问题讨论】:

  • 你知道 Java 和 JavaScript 没有任何关系吧?
  • 其中一半包含在自 1.2 以来的核心语言中,其余大部分在 Java 8 或 Groovy 中可用。
  • @Miguel,是的。它们是完全不同的东西:) 我是 javascript 开发人员,但必须在最近的项目中处理 java 代码。
  • 您是按照下面的建议还是找到了更好的方法来完成 Java 中的函数式编程?

标签: java javascript


【解决方案1】:

有一个图书馆underscore-javaLive example

import com.github.underscore.U;

public class Main {
    public static void main(String args[]) {
        String[] words = {"Gallinule", "Escambio", "Aciform", "Entortilation", "Extensibility"};

        Number sum = U.chain(words)
            .filter(w -> w.startsWith("E"))
            .map(w -> w.length())
            .sum().item();
        System.out.println("Sum of letters in words starting with E... " + sum);
    }
}

// Sum of letters in words starting with E... 34

【讨论】:

    【解决方案2】:

    如果您使用的是 Java 8,则可以使用 Java 的 Stream 类,它有点像 Underscore,因为它是为函数式编程而设计的。 Here are some of the methods available,包括map、reduce、filter、min、max等。

    例如,如果您在下划线中有以下代码:

    var words = ["Gallinule", "Escambio", "Aciform", "Entortilation", "Extensibility"];
    var sum = _(words)
            .filter(function(w){return w[0] == "E"})
            .map(function(w){return w.length})
            .reduce(function(acc, curr){return acc + curr});
    alert("Sum of letters in words starting with E... " + sum);
    

    你可以像这样在 Java 8 中编写它:

    String[] words = {"Gallinule", "Escambio", "Aciform", "Entortilation", "Extensibility"};
    int sum = Arrays.stream(words)
            .filter(w -> w.startsWith("E"))
            .mapToInt(w -> w.length())
            .sum();
    System.out.println("Sum of letters in words starting with E... " + sum);
    

    【讨论】:

      猜你喜欢
      • 2015-04-26
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      相关资源
      最近更新 更多