convert the code with for loop and getting the cus

2019-09-14 13:36发布

问题:

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?

回答1:

I'm not sure this is what you're looking for, but you could do this with two streams:

Stream<myObject> timezones = Arrays.stream(objectArr).filter(obj -> obj.getName().equals("timeZone"));
Stream<myObject> calendars = Arrays.stream(objectArr).filter(obj -> obj.getName().equals("calendar"));
TimeZone timezone = timezones.map(obj -> db.getTmezone(obj.getId())).findAny().get();
CalendarObj calendar = calendars.map(obj -> db.getCalendar(obj.getId())).findAny().get();


回答2:

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 :

    private Object fn(MyObj obj) {
        if (obj.getName().equals("timeZone")) {
            return db.getTmezone(obj.getId());
        } else if (obj.getName().equals("calendar")) {
            return db.getCalendar(obj.getId());
        } else {
            return null;
        }
    }

Then you can use it to collect your required objects:

        List<Object> objects = Arrays
            .stream(objectArr)
            .map(this::fn)
            .filter(Objects::nonNull)
            .limit(2)
            .collect(toList());

So you final list will have at-most 2 objects. But you still to find out the type of the objects, and order.



回答3:

TimeZone timezone = Arrays.stream(objectArr)
.map(obj -> obj.getName().equals("timeZone") ? timezone = db.getTmezone(obj.getId()) : (obj.getName().equals("calendar") ? calendar = db.getTmezone(obj.getId()) : null)) 

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.



标签: lambda java-8