Home>Article>Java> How to use ternary operator to optimize if-else in java

How to use ternary operator to optimize if-else in java

WBOY
WBOY forward
2023-05-02 23:34:11 1471browse

Use ternary operator to optimize if-else

1. Judge the assignment based on if-else conditions, such as:

String id=""; if(flag){ id="a"; }else{ id="b"; }

Use ternary operator symbol, it can be directly optimized into a line of code:

id=flag?"a":"b";

2. Use if-else conditions to determine the calling method, such as:

Set set1=new HashSet<>(); Set set2=new HashSet<>(); if(flag){ set1.add(id); }else{ set2.add(id); }

Use the ternary operator, you can Directly optimized to:

Set set1=new HashSet<>(); Set set2=new HashSet<>(); (flag?set1:set2).add(id);

The above is the detailed content of How to use ternary operator to optimize if-else in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete