我有一个String[],其值如下:

public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

给定字符串s,是否有一种测试VALUES是否包含s的好方法?


当前回答

在Java 8中,使用Streams。

List<String> myList =
        Arrays.asList("a1", "a2", "b1", "c2", "c1");

myList.stream()
        .filter(s -> s.startsWith("c"))
        .map(String::toUpperCase)
        .sorted()
        .forEach(System.out::println);

其他回答

您可以使用Apache Commons Lang中的ArrayUtils.contains

公共静态布尔包含(Object[]数组,Object objectToFind)

注意,如果传递的数组为空,则此方法返回false。

还有一些方法可用于所有类型的基元数组。

例子:

String[] fieldsToInclude = { "id", "name", "location" };

if ( ArrayUtils.contains( fieldsToInclude, "id" ) ) {
    // Do some stuff.
}

开发人员通常会:

Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);

上面的代码可以工作,但不需要先将列表转换为set。将列表转换为集合需要额外的时间。它可以简单到:

Arrays.asList(arr).contains(targetValue);

or

for (String s : arr) {
    if (s.equals(targetValue))
        return true;
}

return false;

第一个比第二个更可读。

可以使用Arrays类对值执行二进制搜索。如果数组未排序,则必须使用同一类中的排序函数对数组进行排序,然后对其进行搜索。

ObStupidAnswer(但我认为这里有一个教训):

enum Values {
    AB, BC, CD, AE
}

try {
    Values.valueOf(s);
    return true;
} catch (IllegalArgumentException exc) {
    return false;
}

一种可能的解决方案:

import java.util.Arrays;
import java.util.List;

public class ArrayContainsElement {
  public static final List<String> VALUES = Arrays.asList("AB", "BC", "CD", "AE");

  public static void main(String args[]) {

      if (VALUES.contains("AB")) {
          System.out.println("Contains");
      } else {
          System.out.println("Not contains");
      }
  }
}