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?
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?
Share Improve this question asked Jan 5, 2015 at 1:53 Nicolas S.XuNicolas S.Xu 14.5k34 gold badges88 silver badges138 bronze badges 4- 5 You realise Java and JavaScript have nothing to do with each other right? – Migwell Commented Jan 5, 2015 at 2:02
- 1 Half of that's included in the core language since 1.2, and much of the rest is available in Java 8 or Groovy. – chrylis -cautiouslyoptimistic- Commented Jan 5, 2015 at 2:19
- @Miguel, yes. They are completely different things:) I was javascript developers, but have to work on java code on recent project. – Nicolas S.Xu Commented Jan 5, 2015 at 2:54
- Did you go ahead with the suggestion below or did you find a better way to accomplish functional programming in Java? – rashadb Commented May 22, 2015 at 1:10
2 Answers
Reset to default 10If 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);
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