Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortening if() with string.equals method

Is there any way to shorten this if() statement? To avoid repeating string.equals() somehow?

if (extension.equals("jpg") || extension.equals("JPG") || extension.equals("png") || extension.equals("PNG") || extension.equals("bmp") || extension.equals("BMP") || extension.equals("jpeg") || extension.equals("JPEG"))
{
    tmp.setIcon(new ImageIcon(getClass().getResource("/menage/Resources/imageIco.png")));
}

To something looking similar to this :

if (extension.equals(("jpg")||("JPG")||("png")||("PNG")||("bmp")||("BMP")||("jpeg")||("JPEG")))
{
    tmp.setIcon(new ImageIcon(getClass().getResource("/menage/Resources/imageIco.png"));)
}

I am aware that this question looks odd, however if() with such long conditions list is unclear and requires a lot of writing as well.

like image 261
baka1408 Avatar asked May 28 '15 14:05

baka1408


2 Answers

Start by changing equals(...) to equalsIgnoreCase(...).

Other options, create a HashSet of lower case Strings (or upper case if desired) with your image extensions and see if it contains your String of interest, changed to lower case:

if (imageExtSet.contains(myExtension.toLowerCase()) {

}
like image 169
Hovercraft Full Of Eels Avatar answered Sep 25 '22 17:09

Hovercraft Full Of Eels


Here is short version with predefined image types:

Set<String> imgTypes = new HashSet<>() {{ 
  add("jpg");   add("JPG");
  add("png");   add("PNG");
  add("bmp");   add("BMP");
  add("jpeg");  add("JPEG");
}};

public boolean isImgType(String type) {
  return imgTypes.contains(type);
}
like image 27
MaxZoom Avatar answered Sep 24 '22 17:09

MaxZoom