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?
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With