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:
Setset1=new HashSet<>(); Set set2=new HashSet<>(); if(flag){ set1.add(id); }else{ set2.add(id); }
Use the ternary operator, you can Directly optimized to:
Setset1=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!