English 中文(简体)
比较一种表述中的多重价值
原标题:Compare one String with multiple values in one expression

我有一份可变数,str,并附有可能的数值,val1 ,val2val3

我愿(同样情况)通过说明(例如):

if("val1".equalsIgnoreCase(str)||"val2".equalsIgnoreCase(str)||"val3".equalsIgnoreCase(str))
{
      //remaining code
}

是否有办法避免使用多种OR(一个操作员)和比较表达的价值观? 例如:

 if(("val1" OR "val2" OR "val3").equalsIgnoreCase(str)   //this is only an idea.
最佳回答

我找到了更好的解决办法。 可通过以下途径实现:

if (str.matches("val1|val2|val3")) {
     // remaining code
}

对于不敏感的配对:

if (str.matches("(?i)val1|val2|val3")) {
     // remaining code
}
问题回答

在Java 8+, 您可使用Stream<T>>>/a>和 ......

if (Stream.of("val1", "val2", "val3").anyMatch(str::equalsIgnoreCase)) {
    // ...
}

如果收藏有<条码>,则你可以把希望将<条码>><>>/条码>与收集和核对所有条码进行比较。 在查询收集情况之前,将收集的所有座标作为下级,并转换为str。 例如:

Set<String> strings = new HashSet<String>();
strings.add("val1");
strings.add("val2");

String str = "Val1";

if (strings.contains(str.toLowerCase()))
{
}

此处采用多种替代物的性能测试(有些是敏感案例,另一些则不敏感):

public static void main(String[] args) {
    // Why 4 * 4:
    // The test contains 3 values (val1, val2 and val3). Checking 4 combinations will check the match on all values, and the non match;
    // Try 4 times: lowercase, UPPERCASE, prefix + lowercase, prefix + UPPERCASE;
    final int NUMBER_OF_TESTS = 4 * 4;
    final int EXCUTIONS_BY_TEST = 1_000_000;
    int numberOfMatches;
    int numberOfExpectedCaseSensitiveMatches;
    int numberOfExpectedCaseInsensitiveMatches;
    // Start at -1, because the first execution is always slower, and should be ignored!
    for (int i = -1; i < NUMBER_OF_TESTS; i++) {
        int iInsensitive = i % 4;
        List<String> testType = new ArrayList<>();
        List<Long> timeSteps = new ArrayList<>();
        String name = (i / 4 > 1 ? "dummyPrefix" : "") + ((i / 4) % 2 == 0 ? "val" : "VAL" )+iInsensitive ;
        numberOfExpectedCaseSensitiveMatches = 1 <= i && i <= 3 ? EXCUTIONS_BY_TEST : 0;
        numberOfExpectedCaseInsensitiveMatches = 1 <= iInsensitive && iInsensitive <= 3 && i / 4 <= 1 ? EXCUTIONS_BY_TEST : 0;
        timeSteps.add(System.currentTimeMillis());
        //-----------------------------------------
        numberOfMatches = 0;
        testType.add("List (Case sensitive)");
        for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
            if (Arrays.asList("val1", "val2", "val3").contains(name)) {
                numberOfMatches++;
            }
        }
        if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
            throw new RuntimeException();
        }
        timeSteps.add(System.currentTimeMillis());

        //-----------------------------------------
        numberOfMatches = 0;
        testType.add("Set (Case sensitive)");
        for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
            if (new HashSet<>(Arrays.asList(new String[] {"val1", "val2", "val3"})).contains(name)) {
                numberOfMatches++;
            }
        }
        if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
            throw new RuntimeException();
        }
        timeSteps.add(System.currentTimeMillis());

        //-----------------------------------------
        numberOfMatches = 0;
        testType.add("OR (Case sensitive)");
        for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
            if ("val1".equals(name) || "val2".equals(name) || "val3".equals(name)) {
                numberOfMatches++;
            }
        }
        if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
            throw new RuntimeException();
        }
        timeSteps.add(System.currentTimeMillis());

        //-----------------------------------------
        numberOfMatches = 0;
        testType.add("OR (Case insensitive)");
        for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
            if ("val1".equalsIgnoreCase(name) || "val2".equalsIgnoreCase(name) || "val3".equalsIgnoreCase(name)) {
                numberOfMatches++;
            }
        }
        if (numberOfMatches != numberOfExpectedCaseInsensitiveMatches) {
            throw new RuntimeException();
        }
        timeSteps.add(System.currentTimeMillis());

        //-----------------------------------------
        numberOfMatches = 0;
        testType.add("ArraysBinarySearch(Case sensitive)");
        for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
            if (Arrays.binarySearch(new String[]{"val1", "val2", "val3"}, name) >= 0) {
                numberOfMatches++;
            }
        }
        if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
            throw new RuntimeException();
        }
        timeSteps.add(System.currentTimeMillis());

        //-----------------------------------------
        numberOfMatches = 0;
        testType.add("Java8 Stream (Case sensitive)");
        for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
            if (Stream.of("val1", "val2", "val3").anyMatch(name::equals)) {
                numberOfMatches++;
            }
        }
        if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
            throw new RuntimeException();
        }
        timeSteps.add(System.currentTimeMillis());

        //-----------------------------------------
        numberOfMatches = 0;
        testType.add("Java8 Stream (Case insensitive)");
        for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
            if (Stream.of("val1", "val2", "val3").anyMatch(name::equalsIgnoreCase)) {
                numberOfMatches++;
            }
        }
        if (numberOfMatches != numberOfExpectedCaseInsensitiveMatches) {
            throw new RuntimeException();
        }
        timeSteps.add(System.currentTimeMillis());

        //-----------------------------------------
        numberOfMatches = 0;
        testType.add("RegEx (Case sensitive)");
        // WARNING: if values contains special characters, that should be escaped by Pattern.quote(String)
        for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
            if (name.matches("val1|val2|val3")) {
                numberOfMatches++;
            }
        }
        if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
            throw new RuntimeException();
        }
        timeSteps.add(System.currentTimeMillis());

        //-----------------------------------------
        numberOfMatches = 0;
        testType.add("RegEx (Case insensitive)");
        // WARNING: if values contains special characters, that should be escaped by Pattern.quote(String)
        for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
            if (name.matches("(?i)val1|val2|val3")) {
                numberOfMatches++;
            }
        }
        if (numberOfMatches != numberOfExpectedCaseInsensitiveMatches) {
            throw new RuntimeException();
        }
        timeSteps.add(System.currentTimeMillis());

        //-----------------------------------------
        numberOfMatches = 0;
        testType.add("StringIndexOf (Case sensitive)");
        // WARNING: the string to be matched should not contains the SEPARATOR!
        final String SEPARATOR = ",";
        for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
            // Don t forget the SEPARATOR at the begin and at the end!
            if ((SEPARATOR+"val1"+SEPARATOR+"val2"+SEPARATOR+"val3"+SEPARATOR).indexOf(SEPARATOR + name + SEPARATOR)>=0) {
                numberOfMatches++;
            }
        }
        if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
            throw new RuntimeException();
        }
        timeSteps.add(System.currentTimeMillis());

        //-----------------------------------------
        StringBuffer sb = new StringBuffer("Test ").append(i)
                .append("{ name : ").append(name)
                .append(", numberOfExpectedCaseSensitiveMatches : ").append(numberOfExpectedCaseSensitiveMatches)
                .append(", numberOfExpectedCaseInsensitiveMatches : ").append(numberOfExpectedCaseInsensitiveMatches)
                .append(" }:
");
        for (int j = 0; j < testType.size(); j++) {
            sb.append(String.format("    %4d ms with %s
", timeSteps.get(j + 1)-timeSteps.get(j), testType.get(j)));
        }
        System.out.println(sb.toString());
    }
}

产出(仅是更糟糕的情况,即何时必须检查所有因素而无一可击):

Test 4{ name : VAL0, numberOfExpectedCaseSensitiveMatches : 0, numberOfExpectedCaseInsensitiveMatches : 0 }:
  43 ms with List (Case sensitive)
 378 ms with Set (Case sensitive)
  22 ms with OR (Case sensitive)
 254 ms with OR (Case insensitive)
  35 ms with ArraysBinarySearch(Case sensitive)
 266 ms with Java8 Stream (Case sensitive)
 531 ms with Java8 Stream (Case insensitive)
1009 ms with RegEx (Case sensitive)
1201 ms with RegEx (Case insensitive)
 107 ms with StringIndexOf (Case sensitive)

Warpspeed SCP提供的产出,将测试改变,以填补休息室外的收集工作,在价值清单无法检测变化时模拟守则(而且收集工作可以重新安排)。

(没有将这一检验时间与先前的测试相比较,因为它是在不同的环境下进行的,但仅比较不同检验战略的时间):

Test 4{ name : VAL0, numberOfExpectedCaseSensitiveMatches : 0, numberOfExpectedCaseInsensitiveMatches : 0 }:
    26 ms with List (Case sensitive)
    6 ms with Set (Case sensitive)
    12 ms with OR (Case sensitive)
    371 ms with OR (Case insensitive)
    14 ms with ArraysBinarySearch(Case sensitive)
    100 ms with Java8 Stream (Case sensitive)
    214 ms with Java8 Stream (Case insensitive)
    773 ms with RegEx (Case sensitive)
    946 ms with RegEx (Case insensitive)
    37 ms with StringIndexOf (Case sensitive)

<代码>ArrayUtils可能有用。

ArrayUtils.contains(new String[]{"1", "2"}, "1")

从 Java9开始,你可以使用以下两种方法:

List.of("val1", "val2", "val3").contains(str.toLowerCase())

Set.of("val1", "val2", "val3").contains(str.toLowerCase());

对于到这里去接受确切的平等检查的人(不忽视案件),我发现:

if (Arrays.asList(str1, str2, str3).contains(strToCheck)) {
    ...
}

如果是最简明的解决办法之一,可在 Java7上查阅。

• 正确使用和书写你自己的静态方法:

public static boolean compareWithMany(String first, String next, String ... rest)
{
    if(first.equalsIgnoreCase(next))
        return true;
    for(int i = 0; i < rest.length; i++)
    {
        if(first.equalsIgnoreCase(rest[i]))
            return true;
    }
    return false;
}

public static void main(String[] args)
{
    final String str = "val1";
    System.out.println(compareWithMany(str, "val1", "val2", "val3"));
}

阿帕奇共同藏书。

StringUtils. EqualsAny (CharSequence string, CharSequence... searchStrings)

因此,就你而言,这将是

StringUtils. EqualsAny(str,“val1”,“val2”,“val3”);

提出了许多解决办法,大多数是可行的解决办法。 然而,我必须在此补充的是,建议使用格外法(>>)的人群(“val1 val1 val2 ±3”)) 是

  1. it s not performant if the method/code is called many times
  2. it s not null safe

我建议使用沥青共同点,即:Lang3 stringUlts, 编号:StringUlts. EqualsAny (str, “val1”, “val2”,“val3” > 。

测试:

public static void main(String[] args) {
        String var = "val1";
        long t, t1 = 0, t2 = 0;

        for (int i = 0; i < 1000; i++) {
            t = System.currentTimeMillis();
            var.matches("val1|val2|val3");
            t1 += System.currentTimeMillis() - t;

            t = System.currentTimeMillis();
            StringUtils.equalsAny(var, "val1", "val2", "val3");
            t2 += System.currentTimeMillis() - t;
        }
        System.out.println("Matches took + " + t1 + " ms
StringUtils took " + t2 + " ms");
    }

1 000英亩后的结果:

Matches took + 18 ms
StringUtils took 7 ms

科特林非常好,无法做到:

setOf("say", "no", "war").contains(your_string)

可以通过收集框架实现这一目标。 你们在一次集约中的所有选择都说,例如<条码> 孔波及;String> Options;

Then loop throgh this to compare your string with the list elements and if it is you can return a boolean value true and otherwise false.

Remember in Java a quoted String is still a String object. Therefore you can use the String function contains() to test for a range of Strings or integers using this method:

if ("A C Viking G M Ocelot".contains(mAnswer)) {...}

人数更多,但仍有工作:

if ("1 4 5 9 10 17 23 96457".contains(String.valueOf(mNumAnswer))) {...} 

由于这个问题已经重新讨论,我也可以提出<条码>enum的解决办法。

enum ValidValues {
   VAL1, VAL2, VAL3;

   public static boolean isValid(String input) {
       return Stream.of(ValidValues.values())
                    .map(ValidValues::name)
                    .anyMatch(s -> s.equalsIgnoreCase(input));
   }
}

或者,你只能用上游声明来做。

Stream.of("val1", "val2", "val3")
      .anyMatch(s -> s.equalsIgnoreCase(str))

如果你只用一个地方的话。

Sorry for reponening this old question, for Java 8+ I think the best solution is the one provided by Elliott Frisch (Stream.of("str1", "str2", "str3").anyMatches(str::equalsIgnoreCase)) but it seems like it s missing one of the simplest solution for eldest version of Java:

if(Arrays.asList("val1", "val2", "val3", ..., "val_n").contains(str.toLowerCase())){
//...
}

你可以通过检查变数(<>代码>>><>>>>>/代码”的非年数,并通过在设定后核对清单,来应用某些错误。

// List of lower-case possibilities
final List<String> list = Arrays.asList("val1", "val2", "val3", ..., "val_n");
for(String str : somethingYouCouldTheReadStringFrom()){
  if(str != null && list.contains(str.toLowerCase())){
    //...
  }
}
boolean contains = "string2".matches(TextUtils.join("|", new String[]{"string1", "string2"}));
!string.matches("a|b|c|d") 

works fine for me.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签