'Want to match json key fields in a json object with items in arraylist and then delete the matching keys

I am relatively new to Java and cant seem to figure out what mistake I'm making. I have a json object.

JSONObject json = new JSONObject();
json.put("alert_test","one");
json.put("Alert_testing","two");
json.put("name","admin");

I Have an arraylist which has just one element in it.

List<String> list = new ArrayList<>();
list.add("alert");

I have written a function to match the key in the json and object with the item in the array list and if the match is successful delete that key and update the jsonObject.

    public static JSONObject jsonObjectDuplicateValues(JSONObject json, List<String> list){

       JSONObject newJson= json;
         list.forEach(name ->
                json.keySet().forEach(keyStr ->
            {
                if(keyStr.toLowerCase().startsWith(name)){
                    json.remove(keyStr);
                    System.out.println(json.toString());
                }
            }));
        System.out.println("outside foreach");
        return newJson;
    }

This is the function call:

        JSONObject check = new JSONObject();
        check = jsonObjectDuplicateValues(json,list);
        System.out.println(check.toString());

The code gives an error inside the function call. Help !



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source