Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 783
Rishabh Bansal Avatar asked Nov 28 '19 07:11

Rishabh Bansal


People also ask

Can you typecast an object in Java?

Type Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind or Object, and the process of conversion from one type to another is called Type Casting.

How do I convert one object to another object in Java 8?

In Java 8, we have the ability to convert an object to another type using a map() method of Stream object with a lambda expression. The map() method is an intermediate operation in a stream object, so we need a terminal method to complete the stream.


1 Answers

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);
like image 167
Eran Avatar answered Oct 13 '22 16:10

Eran