hellzone
hellzone

Reputation: 5236

How to cast lambda method parameters?

I have a lambda expression like below. What I want to ask is Is there any easy way or best practice for casting method parameter?

        results.forEach(
            (result) ->
            {
                ((JSONObject)result).put("test", "test"); 
                ((JSONObject)result).put("time", System.currentTimeMillis());  
                otherList.add(((JSONObject)result));
            }
    );

When I try to change input type like

(JSONObject result) ->

I am getting below error;

incompatible types: Consumer<JSONObject> cannot be converted to Consumer<? super Object>

Upvotes: 6

Views: 24077

Answers (3)

Amad&#225;n
Amad&#225;n

Reputation: 748

The error message explains to you that your list technically–from the compiler's perspective–may contain elements that are not of class JSONObject. Thus you cannot use a Consumer<JSONObject> here. The lambda (JSONObject result) -> ... actually is such an incompatible consumer.

Assuming you have no control over the element type of results you might just map your elements to the correct type before consuming them. In case you expect anything other than only JSONObject elements, you might use the filter() method to omit all incompatible elements and only process the JSONObject instances.

results.filter(JSONObject.class::isInstance) // only needed if you expect non JSONObject elements, too
       .map(result -> (JSONObject) result)
       .forEach(result -> {
         result.put("test", "test"); 
         result.put("time", System.currentTimeMillis());  
         otherList.add(((JSONObject)result));
       });

Upvotes: 6

You can use stream functions in a manner like this to typecast at one step and then query in the subsequent step-

    List<String> collect = Lists.newArrayList(obj.get("graph").getAsJsonObject().get("nodes").getAsJsonArray()).stream().
                map(x -> (JsonObject) x).
                map(x -> {
                    String res = "";
                    try {
                        res = CommonUtils.getAsString(x,"modelKey");
                    } catch (Exception e) {
                    }
                    return res;
                }).collect(Collectors.toList());

Upvotes: 1

Jude Niroshan
Jude Niroshan

Reputation: 4460

As Fabian suggested under the comments, you might have initialized your results like List or List<Object>

What you can do is, you can have List<JSONObject>

results.forEach(
            (result) ->
            {
                result.put("test", "test"); 
                result.put("time", System.currentTimeMillis());  
                otherList.add(result);
            }

Upvotes: 2

Related Questions