我经常使用javascript,并且发现 underscorejs 非常便于操作数据集,例如数组或对象。
我是Java的新手,想知道是否有类似的Java库?
答案 0 :(得分:8)
如果你正在使用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);
答案 1 :(得分:8)
有一个新图书馆:underscore-java。我是该项目的维护者。 Live example
import com.github.underscore.lodash.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);
}
}