Search code examples
javajava-streamclasscastexception

Is there a way to return an Object from stream after Filter? Getting ClassCastException


I want to return an object from a list via a stream.

return (planlinevaluesEntityList != null ? (PlanlinevaluesEntity) planlinevaluesEntityList.stream()
            .filter(p -> p.getMandantKagId()
                    .equals(Long.valueOf(mkId))) : null);

But I get a ClassCastException:

java.lang.ClassCastException: class java.util.stream.ReferencePipeline$2 cannot be cast to class de.pares.int_plan.entity.PlanlinevaluesEntity...

I also tried to use "findFirst()"..

Can anyone tell me what I am doing wrong?


Solution

  • Any Stream operation required a Terminal operation to return anything else than a Stream. In your case, you have multiple choices: findAny() or findFirst(). Both return an Optional<T> that you can unwrap using orElse(null).

    If you need an explicit cast, just like in your question, you can use filter and map like hereunder

    if (planlinevaluesEntityList == null) {
        return null;
    }
    return planlinevaluesEntityList.stream()
                                   .filter(p -> p.getMandantKagId()
                                                 .equals(Long.valueOf(mkId))
                                   )
                                   .filter(PlanlinevaluesEntity.class::isInstance)
                                   .map(PlanlinevaluesEntity.class::cast)
                                   .findFirst()
                                   .orElse(null);