Hello everyone I have the following java code:
TimeZoneObj timezone;
for( myObject obj: objectArr)
{
if((obj.getName).equal("timeZone"))
{
timezone=db.getTmezone(obj.getId());
}
}
and I can successfully convert it to lambada as follows:
TimeZone timezone = Arrays.stream(objectArr)
.filter(obj -> obj.getName().equals("timeZone")) //filters
.map(obj -> db.getTmezone(obj.getId()))
.findAny().oeElse(new TimeZoneObj);
but what if I have else if in my main code:
TimeZoneObj timezone;
CalendarObj calenda;
for( myObject obj: objectArr)
{
if((obj.getName).equal("timeZone"))
{
timezone=db.getTmezone(obj.getId());
}
else if ((obj.getName).equal("calendar"))
{
calendar=db.getCalendar(obj.getId());
}
}
Can anyone help me how to convert above code to lambda?
I'm not sure this is what you're looking for, but you could do this with two streams:
I don't know. It's probably not possible in a way that isn't hacky. I'm presuming you can... get it done with the ternary operator, but the only real do it is Adi Levin said, with two streams.
To answer your question in @Adi Levin's answer, yes, lambda is not for all purpose solution.
Having said that, you can try following:
Create a method to map your array element object to target object :
Then you can use it to collect your required objects:
So you final list will have at-most 2 objects. But you still to find out the type of the objects, and order.