是否有用于 Java 的 underscore.js 库?

Is there a underscore.js lib for java?

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

我是Java新手,不知道有没有类似的Java库?

如果你正在使用Java 8,你可以使用Java的Stream class,它有点像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);

你可以在 Java8 中这样写:

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

有图书馆underscore-java. Live 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