[java] Greater than and less than in one statement

I was wondering, do you have a neat way of doing this ?

if(orderBean.getFiles().size() > 0  && orderBean.getFiles().size() < 5)

without declaring a variable that is not needed anywhere else ?

int filesCount = orderBean.getFiles().size();
if(filesCount > 0  && filesCount < 5) {

I mean, in for loop we are "declaring conditions" for the actual iteration, one can declare a variable and then specify the conditions. Here one can't do it, and neither can do something like

if(5 > orderBean.getFiles().size() > 0)

This question is related to java operators

The answer is


Simple utility method:

public static boolean isBetween(int value, int min, int max)
{
  return((value > min) && (value < max));
}

If this is really bothering you, why not write your own method isBetween(orderBean.getFiles().size(),0,5)?

Another option is to use isEmpty as it is a tad clearer:

if(!orderBean.getFiles().isEmpty() && orderBean.getFiles().size() < 5)

Several third-party libraries have classes encapsulating the concept of a range, such as Apache commons-lang's Range (and subclasses).

Using classes such as this you could express your constraint similar to:

if (new IntRange(0, 5).contains(orderBean.getFiles().size())
// (though actually Apache's Range is INclusive, so it'd be new Range(1, 4) - meh

with the added bonus that the range object could be defined as a constant value elsewhere in the class.

However, without pulling in other libraries and using their classes, Java's strong syntax means you can't massage the language itself to provide this feature nicely. And (in my own opinion), pulling in a third party library just for this small amount of syntactic sugar isn't worth it.


Nowadays you can use lodash:

var x = 1;
var y = 5;
var z = 3;
_.inRange(z,x,y);
//results true

If getFiles() returns a java.util.Collection, !getFiles().isEmpty() && size<5 can be OK.

On the other hand, unless you encapsulate the container which provides method such as boolean sizeBetween(int min, int max).


Please just write a static method somewhere and write:

if( isSizeBetween(orderBean.getFiles(), 0, 5) ){
    // do your stuff 
}

java is not python.

you can't do anything like this

if(0 < i < 5) or if(i in range(0,6))

you mentioned the easiest way :

int i = getFilesSize();
if(0 < i && i < 5){
    //operations

}

of

   if(0 < i){
       if(i < 5){
          //operations
       }
     }

This is one ugly way to do this. I would just use a local variable.

EDIT: If size() > 0 as well.

if (orderBean.getFiles().size() + Integer.MIN_VALUE-1 < Integer.MIN_VALUE + 5-1)