我有一个String[],其值如下:
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
给定字符串s,是否有一种测试VALUES是否包含s的好方法?
我有一个String[],其值如下:
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
给定字符串s,是否有一种测试VALUES是否包含s的好方法?
当前回答
试试看:
ArrayList<Integer> arrlist = new ArrayList<Integer>(8);
// use add() method to add elements in the list
arrlist.add(20);
arrlist.add(25);
arrlist.add(10);
arrlist.add(15);
boolean retval = arrlist.contains(10);
if (retval == true) {
System.out.println("10 is contained in the list");
}
else {
System.out.println("10 is not contained in the list");
}
其他回答
在下面使用-
String[] values = {"AB","BC","CD","AE"};
String s = "A";
boolean contains = Arrays.stream(values).anyMatch(v -> v.contains(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);
如果你不想区分大小写
Arrays.stream(VALUES).anyMatch(s::equalsIgnoreCase);
检查数组是否包含值的四种不同方法
使用列表:公共静态布尔useList(String[]arr,StringtargetValue){return Arrays.asList(arr).contains(targetValue);}使用集合:公共静态布尔useSet(String[]arr,StringtargetValue){Set<String>Set=newHashSet<String>(Arrays.asList(arr));return set。contains(targetValue);}使用简单循环:公共静态布尔useLoop(String[]arr,StringtargetValue){for(字符串s:arr){如果(s.equals(targetValue))返回true;}return false;}使用Arrays.binarySearch():下面的代码是错误的,为了完整起见,这里列出了它。binarySearch()只能用于已排序的数组。你会发现下面的结果很奇怪。这是对数组进行排序时的最佳选项。public static boolean binarySearch(String[]arr,StringtargetValue){return Arrays.binarySearch(arr,targetValue)>=0;}
快速示例:
String testValue="test";
String newValueNotInList="newValue";
String[] valueArray = { "this", "is", "java" , "test" };
Arrays.asList(valueArray).contains(testValue); // returns true
Arrays.asList(valueArray).contains(newValueNotInList); // returns false
Java SE 9的简明更新
引用数组不正确。对于这种情况,我们需要一套。从Java SE 9开始,我们有Set.of。
private static final Set<String> VALUES = Set.of(
"AB","BC","CD","AE"
);
“给定字符串s,是否有测试VALUES是否包含s的好方法?”
VALUES.contains(s)
O(1)。
正确的类型,不可变,O(1)和简洁。漂亮*
原始答案详细信息
只是为了先清除代码。我们已(更正):
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
这是一个可变的静态,FindBugs会告诉你这是非常顽皮的。不要修改静态,也不要允许其他代码这样做。至少,该字段应该是私有的:
private static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
(注意,实际上可以删除新的String[];位。)
引用数组仍然不好,我们需要一个集合:
private static final Set<String> VALUES = new HashSet<String>(Arrays.asList(
new String[] {"AB","BC","CD","AE"}
));
(偏执狂的人,比如我自己,如果这是用Collections.unmodifiedSet包装的话,可能会更放心——然后甚至可以公开。)
(*在品牌方面,集合API仍然可以预见地缺少不可变的集合类型,语法对于我的口味来说仍然过于冗长。)