Program/ Example of Nashorn Javascript (js) Engine in Java 8 - Call java script - Then Create and access java.util.HashMap in javascript >
package nashorn3_hashMap;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
/**
* Call java script - Then Create and access java HashMap in javascript
*
*/
public class Nashorn_useJavaObjects_HashMap_InJavascript {
public static void main(String[] args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
System.out.println("In java - START");
// Call js (javascript) file
engine.eval("load('E:/pocJmse/myNashornJavaScript.js')");
System.out.println("In java - FINISH");
}
}
/* OUTPUT
In java - START
In myNashornScript.js
Step 1 - Create java HashMap in javascript
Step 2 - Initialize java HashMap
Step 3 - Add values in java HashMap
Step 4 - Display java HashMap
{name2=Neha, name1=Ankit}
Step 5 - Display KEYS of java HashMap using for loop
name2
name1
Step 6 - Display VALUES of java HashMap using for each loop
Neha
Ankit
End myNashornScript.js
In java - FINISH
*/
|
E:/pocJmse/myNashornJavaScript.js looks like this >
print('In myNashornScript.js');
print('Step 1 - Create java HashMap in javascript');
var javaHashMap = Java.type('java.util.HashMap');
print('\nStep 2 - Initialize java HashMap');
var myJavaHashMap = new javaHashMap();
print('\nStep 3 - Add values in java HashMap');
myJavaHashMap.put('name1', 'Ankit');
myJavaHashMap.put('name2', 'Neha');
print('\nStep 4 - Display java HashMap');
print(myJavaHashMap);
print('\nStep 5 - Display KEYS of java HashMap using for loop');
for each(var keys in myJavaHashMap.keySet()){
print(keys);
}
print('\nStep 6 - Display VALUES of java HashMap using for each loop');
for each(var values in myJavaHashMap.values()){
print(values);
}
print('\nEnd myNashornScript.js');
|
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.