vincent
vincent

Reputation: 25

Java Stream#map apparently doesn't work anymore

I am currently working on a deserialization of multiple processes within a single object. The thing is that I pass a Collection as the object parameter. Everything works fine -> I get the regular output of:

Deserialize object [testCollection] with type argument java.lang.String
Object is collection.

Now, throughout the mapping procedure in a Stream, I should get the output of every element within the object that has been identified as a collection, as wanted. So I should get the following output:

Deserialize object [testCollection] with type argument java.lang.String
Object is collection.
Deserialize object testCollection with type argument java.lang.String

as testCollection is the only element within the collection. But I don't get any input afterwards. I tried printing every element in forEach, which actually worked. But mapping doesn't.

Maybe someone knows how I could fix this problem, maybe I am too tired of seeing the issue :D

    @Recursive("_, Collection")
    public static Object prepareDeserialization(Class<?> typeClass, Object object) {
        System.out.printf("Deserialize object %s with type argument %s%n", object, typeClass);
        //Check if the object could be a collection
        if (isCollection(objectClass)) {
            System.out.println("Object is collection.");
            return (((Collection<?>) object)).stream()
                    .map((e) -> prepareDeserialization(typeClass, e));
        }

Upvotes: 0

Views: 418

Answers (1)

Anderson
Anderson

Reputation: 169

The function map is lazy, in the sense that it won't produce you a final result. It will produce a new Stream, that once consumed will map its input with the function.

The keyword here is consumed.

In a Stream you consume it with the method collect. The simples example would be this:

if (isCollection(objectClass)) {
    System.out.println("Object is collection.");
    return (((Collection<?>) object)).stream()
            .map((e) -> prepareDeserialization(typeClass, e))
            .collect(Collectors.toList()); // <- now your result is a list, that will contain the "mapped" objects
}

Upvotes: 2

Related Questions