Is there a underscore.js lib for java?

I use javascript often, and find underscorejs is very handy for manipulating data set, such as array or object.

I am very new to Java, and wonder if there is similar lib for Java?

Answer

If you’re using Java 8, you can use Java’s Stream class, which is a bit like Underscore in that it’s designed for functional programming. Here are some of the methods available, including map, reduce, filter, min, max etc.

For example if you had the following code in 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);

You could write it in Java 8 like this:

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