yellow
yellow

Reputation: 455

Assign value from if condition to a variable if true with in condition itself in Java

Let me start with my condition,

 protected void populateBags(ListOfBagsType listOfBags, BagHasButtons bagHasButtons)
      if (null != listOfBags && null != listOfBags.getBags()) {
          List<Bags> bags = listOfBags.getBags();
            if (null != bags.get(0).getColors().getColor().get(0) && bagsWithButtons != null && null != bagHasButtons.getBagsWithButtons().get(0)) {
             // do process
        }
    }
}

My question here, is there a way assign the value of listOfBags.getBags() to a variable if the condition is true, like

 List<Bags> bags = null;
 if (null != listOfBags && (null != listOfBags.getBags() = bags))

instead of assigning it in the next line of code? I am not sure how to use ternery operators here. If that works I can use the same for the next if condition and process the variables later.

Upvotes: 0

Views: 1698

Answers (2)

Paul Renauld
Paul Renauld

Reputation: 186

To add to Roddy's answer, another solution would be:

List<Bags> bags = null != listOfBags? listOfBags.getBags(): null;
if (nbags != null)

Upvotes: 0

Roddy of the Frozen Peas
Roddy of the Frozen Peas

Reputation: 15179

While less readable, this is precisely what the ternary operator is for.

List<Bags> bags = (listOfBags != null && listOfBags.getBags() != null) ? listOfBags.getBags() : null;

I personally would have stuck with a simple if-statement because it's more readable:

List<Bags> bags = null;
if(listOfBags != null && listOfBags.getBags() != null) {
  bags = listOfBags.getBags();
}

Both do the same thing.


You could, of course, try to make the ternary operator more readable by extracting a boolean representing the conditional ...

boolean hasBags = listOfBags != null && listOfBags.getBags() != null;
List<Bag> bags = hasBags? listOfBags.getBags() : null;

... but that that point you might as well just use an if-statement.

Upvotes: 2

Related Questions