Java有没有类似于underscore.js的库?

9
我经常使用 JavaScript,并发现 underscorejs 在操作数据集(如数组或对象)方面非常方便。
我对 Java 很陌生,想知道是否有类似的库?

5
你知道Java和JavaScript没有任何关系,对吧? - Migwell
1
自1.2版本以来,其中一半已包含在核心语言中,其余部分大部分可在Java 8或Groovy中使用。 - chrylis -cautiouslyoptimistic-
@Miguel,是的。它们完全是不同的东西:) 我曾经是JavaScript开发人员,但最近的项目需要我处理Java代码。 - Nicolas S.Xu
你是按照下面的建议继续进行了,还是找到了更好的方法来实现Java中的函数式编程? - rashadb
2个回答

10
如果您正在使用Java 8,您可以使用Java的Stream类,它有点像Underscore,因为它是为函数式编程而设计的。以下是部分可用方法, 包括map、reduce、filter、min、max等。
例如,如果您在Underscore中有以下代码:
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);

10

有一个叫做underscore-java的库。示例

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接