Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast call in map stream operation not working [duplicate]

I have the following (using org.json.simple):

 import org.json.simple.JSONArray;
 import org.json.simple.JSONObject;
 ...
 final JSONArray results = (JSONArray) responseObject.get("results");
 results
        .stream()
        .filter(JSONObject.class::isInstance)
        .map(JSONObject.class::cast)
        .map(obj -> obj) // obj is still Object here, not JSONObject?

The problem is that after I call map to cast the stream elements to JSONObject, on the next call to map, the elements are still Object, not JSONObject. Not sure what I'm doing wrong here?

Related: Is it possible to cast a Stream in Java 8?

like image 543
rmf Avatar asked Oct 22 '25 04:10

rmf


1 Answers

org.json.simple.JSONArray extends java.util.ArrayList, which means it extends a raw type.

As a result, results.stream() returns a raw Stream instead of a Stream<SomeElementType>, and even after the calls to map(), you still get a raw Stream, so the casting doesn't help you.

If org.json.simple.JSONArray extended ArrayList<Object> instead, you would have gotten a Stream<Object>, and after the call to .map(JSONObject.class::cast), a Stream<JSONObject>.

I believe you should be able to get over that with the following unchecked cast:

final JSONArray results = (JSONArray) responseObject.get("results");
List<Object> genericResults = (List<Object>) results;
List<JSONObject> list =
    genericResults.stream()
                  .filter(JSONObject.class::isInstance)
                  .map(JSONObject.class::cast)
                  .collect(Collectors.toList());
like image 176
Eran Avatar answered Oct 23 '25 19:10

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!