How to cast lambda method parameters?

允我心安 提交于 2021-02-08 03:57:15

问题


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>

回答1:


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));
       });



回答2:


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);
            }



回答3:


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());


来源:https://stackoverflow.com/questions/39390550/how-to-cast-lambda-method-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!