Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map an object stream to a specific type

Tags:

java

java-8

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?

like image 999
Rogue Avatar asked Aug 03 '14 20:08

Rogue


People also ask

How would you create a map from List of objects using streams?

Convert the List into stream using List. stream() method. Create map with the help of Collectors. toMap() method.

What is map method in stream?

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.

How do I map an object in Java 8?

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.


2 Answers

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.

like image 91
Sotirios Delimanolis Avatar answered Oct 10 '22 07:10

Sotirios Delimanolis


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
});
like image 40
fabian Avatar answered Oct 10 '22 07:10

fabian