Created
August 13, 2014 01:43
-
-
Save danveloper/5698b32dd337623d49b6 to your computer and use it in GitHub Desktop.
Collection Stream Processing in JavaScript with Java 8 & Nashorn
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Reference to ArrayList type | |
var List = Java.type("java.util.ArrayList"); | |
// An interface that provides default implementations for java.util.function.{Consumer,Function} | |
var ConsumingFunction = Java.type("midwestjs.nashorn.ConsumingFunction"); | |
// Convert appropriately | |
function toFunc(fn) { | |
return new ConsumingFunction() { | |
apply: function(a) { | |
return fn(a); | |
}, | |
accept: function(a) { | |
fn(a); | |
} | |
} | |
} | |
(function() { | |
var list = new List(); | |
list.add(1); | |
list.add(2); | |
list.add(3); | |
list.stream() | |
.map(toFunc(function(a) { return a * 2; })) | |
.forEach(toFunc(function(a) { print(a); })); | |
})(); |
Even better... @BenjaminMalley pointed out that the function wrappers aren't necessary!
// Reference to ArrayList type
var List = Java.type("java.util.ArrayList");
// An interface that provides default implementations for java.util.function.{Consumer,Function}
var ConsumingFunction = Java.type("midwestjs.nashorn.ConsumingFunction");
// Convert appropriately
function toFunc(fn) {
return new ConsumingFunction() {
apply: fn,
accept: fn
}
}
(function() {
var list = new List();
list.add(1);
list.add(2);
list.add(3);
list.stream()
.map(toFunc(function(a) { return a * 2; }))
.forEach(toFunc(function(a) { print(a); }));
})();
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result: