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

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

WBOY
Release: 2023-05-02 23:34:11
forward
1571 people have browsed it

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";
}
Copy after login

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

id=flag?"a":"b";
Copy after login

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

Set<String> set1=new HashSet<>();
Set<String> set2=new HashSet<>();

if(flag){
    set1.add(id);
}else{
    set2.add(id);
}
Copy after login

Use the ternary operator, you can Directly optimized to:

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

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template