1

I have some JavaScript code that I currently run on Java 7 using the Rhino engine. Now I want to migrate the code to Java 8 (and therefore execute it with the Nashorn engine). The constraint is that the JavaScript code should only be changed in a way that it can still be run on Java 7 & Rhino.

Now I am struggling with the use of the Array.prototype.forEach() function. I am using the following pattern several times:

myJavaObject.getJavaSet().toArray().forEach(
    function(element){
        foo(element);
    }
}

This works well with Rhino since Rhino seem to use the JavaArray as JavaScript Array and runs the JavaScript Array.prototype.forEach() function.

Nevertheless when using Rhino this approach does not work anymore. Instead I found out that I would need to run the forEach function of Java 8 on the object of type Iterable interface. So I need to skip calling the toArray() method:

myJavaObject.getJavaSet().forEach(
    function(element){
        foo(element);
    }
}

To sum it up, the first code snippet runs fine with Java 7 and Rhino (but not with Java 8 and Nashorn) and the second snippet works well with Java 8 (but not 7).

Since I need to have a code that runs on both engines, both options are not a solution. I found out a third way, which IS actually running on both engines namely the for each loop:

for each (element in myJavaObject.getJavaSet().toArray()){
    foo(element);
}

But since the "for each" loop is deprecated, I would rather prefer to use another solution to not have to migrate my code again in near future. So I am looking for a better solution for a forEach loop that is running on both, Java 7 and Java 8. Thanks for any of your ideas!

1 Answer 1

0

If it is backed by a Java collection, I suggest to use this:

var iterator = myJavaObject.getJavaSet().iterator();
while (iterator.hasNext()) {
    print(it.next());
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.