How to remove element from Java Map from within Nashorn JavaScript

Viewed 633

I have a Java HashMap which I have passed to the script engine. I would like to remove entries as they are processed because I'm reporting invalid keys later. The apparent usual method for removing entries (delete testMap['key'];) has no effect.

How do I make this test pass?

@Test
public void mapDelete() throws ScriptException{
    Map<String,String> map = new HashMap<>(1);
    map.put("key","value");

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
    engine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE).put ("testMap", map);
    engine.eval("delete testMap['key'];");
    Assert.assertEquals (0, map.size());
}
1 Answers

If you know that you have an HashMap, you can use its Map API within Nashorn, i.e.:

@Test
public void mapDelete() throws ScriptException {
    Map<String,String> map = new HashMap<>(1);
    map.put("key","value");

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
    engine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE).put ("testMap", map);
    engine.eval("testMap.remove('key');");
    Assert.assertEquals (0, map.size());
}
Related