0

I want to add the below condition with java in Ireport:

Field.equals("red" or "bleu" or "black" or "....") ? "yes" : "no"

Do I have to use

Field.equals("..")||$F{color}.equals("..")

I have a long list. Is there any other way to express it?

Alex K
  • 22,315
  • 19
  • 108
  • 236
Aya
  • 31
  • 3

3 Answers3

5

Approach #1:

private static final HashSet<String> colors = new HashSet<>(
    Arrays.asList("red", "blue", "black", "sky-blue pink"));

res = (colors.contains(field)) ? "yes" : "no";

Approach #2 (Java 7 and later)

switch (field) {
case "red": case "blue": case "black": case "sky-blue pink": 
    res = "yes";
    break;
default:
    res = "no";
}

Approach #3 (Java 12 or later)

res = switch (field) {
    case "red", "blue", "black", "sky-blue pink" -> "yes";
    default -> "no";
};

The performance of the three approaches should be about the same. Under the hood, string switch statements and switch expressions will typically use the equivalent of a static HashMap to map from the field value to either a value or a jump address. However, if performance really matters to you, benchmark the alternatives in the context of your application (after profiling, etc).

To my mind, the last approach is the neatest ... if you have the freedom to use Java 12+. The first approach has the possible advantage that the list of strings doesn't need to be hard-wired into your codebase.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
2

Keep a list of all the strings that you want to compare Field against

List<String> list = Arrays.asList("red","blue","green");
return list.contains(field) ? "yes" : "no";
Gautham M
  • 4,816
  • 3
  • 15
  • 37
0

Here is another way:


public class Main
{
    public static void main(String[] args) {

        String field = "brown";
        switch(field) {
            case "blue":
            case "black":
            case "red":
            case "yellow":
               System.out.println("Color :"+field);
            break;
            default:
                System.out.println("Not found");

        }
    }
}
Majid Hajibaba
  • 3,105
  • 6
  • 23
  • 55