Debo
Debo

Reputation: 41

Java add bean to different list based on null check

I have below code:

List<String> successfullLIst=new ArrayList();
List<String> failedList=new ArrayList();

MyBean myBean=saveindb(accountId);
if(myBean!=null){
    successfullLIst.add(myBean.getAccountid());
}else{
    failedList.add(accountid);
}

I want to avoid this if loop.can this be done without using if/else loop as there are already so many if else present in my code. PLease help

Upvotes: 0

Views: 209

Answers (2)

pcsutar
pcsutar

Reputation: 1831

You can use try-catch to solve your purpose:

List<String> successfullLIst=new ArrayList();
List<String> failedList=new ArrayList();

try
{
    MyBean myBean=saveindb(accountId);
    successfullLIst.add(myBean.getAccountid()); //line no. 7
}
catch(NullPointerException e)
{
    failedList.add(accountid);
}

If your myBean object is null then line no. 7 i.e. successfullLIst.add(myBean.getAccountid()); will throw NullPointerException. Then you can add your accountid to failed list inside catch block as shown in above example.

Hope this will work!

Upvotes: 0

Remo
Remo

Reputation: 604

Java 9+

Pass to Optional#ifPresentOrElse a lambda that calls List#add.

Optional
    .ofNullable(myBean)
    .ifPresentOrElse(
        it -> successfullLIst.add(it.getAccountid()), 
        () -> failedList.add(accountId)
    )
;

Java 8

Alternatively, we can use the ternary operator. The List#add method returns a boolean.

boolean b = 
    Objects.nonNull(myBean) ? 
        successfullLIst.add(myBean.getAccountid) : 
        failedList.add(accountId)
;

Upvotes: 1

Related Questions