Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Collection Stream Processing in JavaScript with Java 8 & Nashorn
// 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); }));
})();
@danveloper
Copy link
Author

danveloper commented Aug 13, 2014

Result:

2
4
6

@danveloper
Copy link
Author

danveloper commented Aug 13, 2014

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