Nicolas S.Xu
Nicolas S.Xu

Reputation: 14534

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?

Upvotes: 9

Views: 6913

Answers (2)

Valentyn Kolesnikov
Valentyn Kolesnikov

Reputation: 2097

There is a library 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

Upvotes: 10

Migwell
Migwell

Reputation: 20117

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

Upvotes: 10

Related Questions