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?
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With