I have a JSONArray
of objects, and I want to map each object to a JSONObject
.
I tried:
JSONArray array; //my json array
array.stream().map(obj -> (JSONObject) obj).forEach((JSONObject prof) -> {
//code
});
However the type is already encapsulated by Object
and thus I cannot seem to cast it down. How can I achieve this with Java 8 streams?
Convert the List into stream using List. stream() method. Create map with the help of Collectors. toMap() method.
The map() function is a method in the Stream class that represents a functional programming concept. In simple words, the map() is used to transform one object into other by applying a function. That's why the Stream. map(Function mapper) takes a function as an argument.
Java 8 stream map() map() method in java 8 stream is used to convert an object of one type to an object of another type or to transform elements of a collection. map() returns a stream which can be converted to an individual object or a collection, such as a list.
A few issues here. JSONArray
is a raw sub type of ArrayList
. Therefore the methods it inherits are also raw, all their type parameter uses are erased and reduce to Object
. Just that should tell you that things will not be safe going forward.
The invocation of
array.stream().map(..)
is raw. Therefore the Function
that map
accepts will also be raw. The returned Stream
will also be raw. And therefore the forEach
invoked will operate on Object
, the resulting type from erasure. There's nothing you can do about this except for casting in between operations. Something like
Stream stream = array.stream().map(obj -> (JSONObject) obj);
((Stream<JSONObject>) stream).forEach((JSONObject prof) -> {
// code
});
But this is in no way safe (unless you know there are only JSONObject
objects in the JSONArray
). Which brings us to...
I have a JSONArray of objects, and I want to map each object to a JSONObject.
You have to decide how to do this mapping. JSONArray
can contain JSONObject
, Strings, numbers, etc. Simply casting to a JSONObject
won't work.
Your code won't work, since the ArrayList
that is the base type of JSONArray
has no type parameter specified. You can simply "add" one by casting:
((List<?>)array).stream().map(obj -> (JSONObject) obj).forEach((JSONObject prof) -> {
//code
});
But in your code example I really don't see any reason not to use only one lambda expression like this:
array.stream().forEach(obj -> {
JSONObject prof = (JSONObject) obj;
//code
});
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