Java Reference
In-Depth Information
Uses the Java
List.sort() method to sort the elements in natural
order
Uses the
Array.prototype.forEach() method to print the sorted
elements
Using a Java Map as a Nashorn Object
You have seen that Nashorn objects are simply maps storing string-object pairs. Nashorn
allows using a Java Map as a Nashorn object in which you can use keys in the Map as the
properties of the object. Listing 7-5 shows how to use a Java Map as a Nashorn object.
Listing 7-5. Using a Java Map as a Nashorn Object
// map.js
// Create a Map instance
var HashMap = Java.type("java.util.HashMap");
var map = new HashMap();
// Add key-value pairs to the map using Java methods
map.put("Li", "999-11-0001");
map.put("Su", "999-11-0002");
// You can treat the Map as an object and add key-value pairs
// as if you are adding proeprties to the object
map["Yu"] = "999-11-0003";
map["Do"] = "999-11-0004";
// Access values using the Java Map.get() method and the bracket notation
var liPhone = map.get("Li"); // Java way
var suPhone = map.get("Su"); // Java way
var yuPhone = map["Yu"]; // Nashorn way
var doPhone = map["Do"]; // Nashorn way
print("Li's Phone: " + liPhone);
print("su's Phone: " + suPhone);
print("Yu's Phone: " + yuPhone);
print("Do's Phone: " + doPhone);
Li's Phone: 999-11-0001
su's Phone: 999-11-0002
Yu's Phone: 999-11-0003
Do's Phone: 999-11-0004
 
Search WWH ::




Custom Search