Access JSONObject field value in lambda expression

I am pretty new to Java and I am quite found of fonctional programming. Here I am trying to write the most concise factory method to create a List<Manager> based on a JSONArray retrieved from an API. Here is a simplified version of what I have in mind

public List<Manager> getManagers(HashMap parameters) throws IOException, InterruptedException {
    JSONArray records = (JSONArray) api.getData("Manager", parameters).get("records");
    records.forEach(x -> new Manager(x.get("FirstName"),x.get("LastName")))

and how I would do it in python (I am highly biased)

manager_list = list(map(lambda x: Manager(x["FirstName"],x["LastName"]),records))

I am experiencing two issues.

  1. access JSONObject fields inside the lambda expression

Despite x being a JSONObject

records.forEach(x -> System.out.println(x.getClass()));
class org.json.JSONObject

x.get("FirstName") does not work in the lambda. Is it because .get() is an instance method or am I missing something else?

  1. easily append Managers to a list

This does not work

List managers = records.forEach(x -> new Manager(x.get("FirstName"),x.get("LastName")))

because forEach returns void. Does forEach have a cousin who could return any kind of Interable or Collection ?

Since I am new to java, I both interested in implementations for my actual problem and more general discussions on functional programming in modern java

Answer

Try the following:

public List<Manager> getManagers(HashMap parameters) throws IOException, InterruptedException {
        
    JSONArray records = (JSONArray) api.getData("Employee", parameters).get("records");

    List<Manager> managers = new ArrayList<>();
    records.forEach(jsonRecord -> {
        JSONObject record = (JSONObject) jsonRecord;
        managers.add(new Manager(record.getString("FirstName"), record.getString("LastName")));
    });

    return managers;
    }

You may have to cast each item into a JSONObject in order to access the properties.

Leave a Reply

Your email address will not be published. Required fields are marked *