Rishabh Bansal
Rishabh Bansal

Reputation: 392

How to typecast an object in the java Stream API?

How can I typecast an object inside the nested list's Object -:

C c = GenericScreenDataBean fieldObjx = this.expenseLineItemList.stream()
                .flatMap(a -> a.getSectionModel().getControls().stream())
                .filter(b -> b.getData() instanceof GenericScreenDataBean)
                .map(GenericScreenDataBean.class::cast)
                .filter(c->c.getFieldKey().equals("IncurredAmount")).findAny().orElse(null);

As the code mentioned above, Following is the descriptions-:

List<expenseLineItemList> is the master List for which I am invoking the stream API, then I am streaming on the List<Controls>.

Now, the data getObject() in the Controls class is the type of Object which I am trying to typecast here. As the map function map(GenericScreenDataBean.class::cast) will cast the Controls.class, I am getting the typecasting exception.

So, instead of typecasting the Controls.class, how can I typecast the getControls().getObject() and filter out the desired result?

Upvotes: 6

Views: 266

Answers (1)

Eran
Eran

Reputation: 393831

It appears you are missing a map step:

C c = GenericScreenDataBean fieldObjx = this.expenseLineItemList.stream()
                .flatMap(a -> a.getSectionModel().getControls().stream())
                .filter(b -> b.getData() instanceof GenericScreenDataBean)
                .map(Controls::getData)
                .map(GenericScreenDataBean.class::cast)
                .filter(c->c.getFieldKey().equals("IncurredAmount")).findAny().orElse(null);

Or, if you want a single map, you can use a lambda expression instead of method references:

C c = GenericScreenDataBean fieldObjx = this.expenseLineItemList.stream()
                .flatMap(a -> a.getSectionModel().getControls().stream())
                .filter(b -> b.getData() instanceof GenericScreenDataBean)
                .map(c -> (GenericScreenDataBean) c.getData())
                .filter(c->c.getFieldKey().equals("IncurredAmount")).findAny().orElse(null);

Upvotes: 4

Related Questions