How to remove an item from a Java map from Nashorn JavaScript code

I have a Java HashMap that I passed to the script engine. I would like to delete entries as they are processed, because later I report about invalid keys. The obvious regular method for deleting records ( delete testMap['key'];) has no effect.

How do I pass this test?

@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());
}
+4
source share
1 answer

If you know what you have HashMap, you can use the maps API in Nashorn, that is:

@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());
}
+3
source

Source: https://habr.com/ru/post/1686403/


All Articles