Bootstrap
本文主要介绍Java中条件判断时,if条件中有多个字符串需要比较,条件比较多的简单写法。

一般较复杂的写法

if(pouch.getStatus().equals("Finalized") || pouch.getStatus().equals("Ready") 
|| pouch.getStatus().equals("Checkout") || pouch.getStatus().equals("Confirmed")
|| pouch.getStatus().equals("Book") || pouch.getStatus().equals("Started")
|| pouch.getStatus().equals("Inital") || pouch.getStatus().equals("Close")) {
// Body
}

1、使用matches实现

if(pouch.getStatus().matches("Finalized|Ready|Checkout|Confirmed|Book|Started|Inital|Close")){
//your implementation goes here
}

2、使用字典集合判断

1)在集合中添加多个条件,从中实现 Collection<E>

Set<String> dict = new HashSet<String>();
dict.add("Finalized");
dict.add("Ready");
dict.add("Checkout");
dict.add("Confirmed");
dict.add("Book");
dict.add("Started");
dict.add("Inital");
dict.add("Close");

2)contains检查输入值是否存在于集合中

if (dict.contains(pouch.getStatus()))
{
// do your logic
}

3、使用Stream实现判断

String status = pouch.getStatus();
if (Stream.of(
"Finalized",
"Ready",
"Checkout",
"Confirmed",
"Book",
"Started",
"Inital",
"Close")
.anyMatch(status::equals)) {
// Body
}

4、使用Arrays.asList()通过数组判断

 public String[] statusArray = new String[]{  "Finalized", "Ready","Checkout","Confirmed",  "Book",  "Started", "Inital", "Close"};
if( Arrays.asList(statusArray).contains(pouch.getStatus())){
//do something
}

// Java 9 way of initializing List with one line        
List<String> statuses = List.of("Finalized", "Ready", "Checkout", "Confirmed",
    "Book", "Started", "Inital", "Close");
if (statuses.contains(pouch.getStatus())) {
  // Body
}

5、使用switch case判断

switch (pouch.getStatus()) {
case "Finalized":
case "Ready":
case "Checkout":
case "Confirmed":
case "Book":
case "Started":
case "Inital":
case "Close":
// your code break;
}