17

I have multiple conditions to check as shown below,

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 Implementation
}

Is there any easy way to check above conditions similar like SQL INcondition, so that code look simpler?

Santosh Jadi
  • 1,479
  • 6
  • 29
  • 55
  • 1
    See [Does Java have a β€œIN” operator or function like SQL?](https://stackoverflow.com/questions/3565954/does-java-have-a-in-operator-or-function-like-sql). This is clearly a duplicate. – AxelH Aug 29 '18 at 07:55

13 Answers13

13

Let's take a look about SQL in features

SQL WHERE IN returns values that match values in a list


So I would use a collection, which implements from Collection<E> and had contains method, make the if statement simpler.

contains(Object o) Returns true if this set contains the specified element.

contains effect is very similar to SQL in.


1.add your multiple conditions in the collection, which implements from 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.using contains to check input value whether exist in the collection.

if (dict.contains(pouch.getStatus()))
{
     // do your logic
}
D-Shih
  • 44,943
  • 6
  • 31
  • 51
6

You can use the method matches which is available in String class,

if(pouch.getStatus().matches("Finalized|Ready|Checkout|Confirmed|Book|Started|Inital|Close")){
   //your implementation goes here
}
Praveen
  • 1,791
  • 3
  • 20
  • 33
5
List<String> listOfInputs = new ArrayList<String>();
// add elements in listOfInputs...  
boolean isAvailable = listOfInputs.contains(pouch.getStatus());
davidxxx
  • 125,838
  • 23
  • 214
  • 215
raviraja
  • 676
  • 10
  • 27
5

SQL IN might return more than one result, but in your question, if one condition is satisfied the operation will terminate and return.

You can create an enum to hold all your conditions as shown below.

Assuming your Pouch class is this.

public class Pouch {

    private final String status;

    public Pouch(final String status) {
        this.status = status;
    }

    public String getStatus() {
        return status;
    }
}

Here is your enum with the pouch status.

public enum  PouchEnum {
   Finalized, Ready, Checkout, Confirmed, Book, Started, Inital, Close
}

and check your condition as shown below.

if (PouchEnum.valueOf(pouch.getStatus()) != null) {
        // Do some stuff
}

To make it cleaner you can use EnumUtils from apache commons-lang3 this make your code checking more cleaner as shown below.

if (EnumUtils.isValidEnum(PouchEnum.class, pouch.getStatus())) {
        // Do some stuff
}

I hope this will help your code to be cleaner.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
bellomd
  • 81
  • 1
  • 5
4

You can create custom function:

static boolean inCondition(String var, String... ins) {
    for (String in : ins) {
        if (in.equals(var)) return true;
    }

    return false;
}

and then use it in this way:

public static void main(String[] args) {
    String pouch = "Ready";
    if (inCondition(pouch, "Finalized", "Ready", "Checkout" ... )) {
        // do something
    }
}
Maxim
  • 1,194
  • 11
  • 24
4

Below snippet might help you.

 String status = "COMPLETED";
 List<String> statusList = new ArrayList<>(Arrays.asList("COMPLETED","INPROGRESS"));
 if(statusList.contains(status)){
     // do your stuff
 }
davidxxx
  • 125,838
  • 23
  • 214
  • 215
3

Using Arrays.asList and then use contains might be the best way at least on my case.

if(Arrays.asList("Finalized", "Ready", "Checkout", "Confirmed", 
    "Book", "Started", "Inital", "Close").contains(pouch.getStatus())) {

   // Body
}
Akashah Amin
  • 113
  • 2
  • 11
2

I think if you use the "switch" conditional, the code reads better:

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

For this particular scenario, I think it's a good candidate for a simple enum like this:

public enum PouchStatus {
    FINALIZED, READY, CHECKOUT, CONFIRMED, BOOK, STARTED, INITIAL, CLOSE
}

Usage:

if(PouchStatus.valueOf(pouch.getStatus().toUpperCase()) != null) {
}

You can also move this string sanitizing logic inside a static method in the enum, which would look like this:

public enum PouchStatus {
    FINALIZED, READY, CHECKOUT, CONFIRMED, BOOK, STARTED, INITIAL, CLOSE

    public static PouchStatus fromDescription(String desc) {
        return Arrays.stream(PouchStatus.values()).filter(e -> e.name().equalsIgnoreCase(desc)).findFirst().orElse(null);
    }
}

Usage:

if (PouchStatus.fromDescription(pouch.getStatus()) != null) {
}

As a final note, if the Pouch object comes from ORM (e.g.: hibernate/jpa) you can just map these values to the according enum elements right in the entity mapping (pouc.getStatus() would already return a PouchStatus object instead of a String).

everton
  • 7,579
  • 2
  • 29
  • 42
1

Here is full example

public class InConditionJava {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String[] arr = { "Finalized", "Ready", "Checkout" };
        checkData(arr);
    }

    private static void checkData(String[] arr) {
        Set<String> names = new HashSet<String>(Arrays.asList(arr));

        System.out.println("AS Checkout is there in our arr is should return True>>" + names.contains("Checkout")); // true
        System.out.println(names.contains("Book")); // false
    }

}

Eclipse demo

Vipul Gulhane
  • 761
  • 11
  • 16
1

There are already plenty of options here, but you could also use Stream for this task, if the version of the JDK you are using is >= 8:

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

The downside of this method, compared to Collection#contains, is that you must make sure that pouch.getStatus() is not null, otherwise you will get a NullPointerException.

Gustavo Passini
  • 2,348
  • 19
  • 25
1

Here is another way of initializing List in one line with all statuses, and then checking if the list contains the given status.

// 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
}
Pradip Karki
  • 662
  • 1
  • 8
  • 21
1

You can create an array of all status, then check if pouch.getStatus() in in that list or not?

 public String[] statusArray = new String[]{  "Finalized", "Ready","Checkout","Confirmed",  "Book",  "Started", "Inital", "Close"};

if( Arrays.asList(statusArray).contains(pouch.getStatus())){
 //do something 
}
patidarsnju
  • 439
  • 5
  • 10