Java中检查数组是否包含某元素
学习检查数组是否包含元素。另外,学习查找数组中元素的索引。
1. 使用Arrays类
要检查某个元素是否在数组中,我们可以使用Arrays类将数组转换为ArrayList,并使用该contains()
方法检查该项目是否存在。另外,我们可以使用该indexOf()
方法来查找数组中项目的索引。
对于自定义对象数组,使用equals()方法检查对象相等性,以便对象在重写的equals()方法中实现了正确且预期的相等规则。
字符串和包装类已经重写了equals()方法,因此它们可以正常工作。
//检查数组是否包含元素 String[] fruits = new String[] { "banana", "guava", "apple", "cheeku" }; Arrays.asList(fruits).contains("apple"); // true Arrays.asList(fruits).indexOf("apple"); // 2 Arrays.asList(fruits).contains("lion"); // false Arrays.asList(fruits).indexOf("lion"); // -1
2. 使用Streams
从Java 8开始,我们可以从数组创建一个项目流并测试该流是否包含给定的项目。
我们可以使用stream.anyMatch()方法返回该流的任何元素是否与提供的Predicate匹配。在Predicate中,检查流中当前元素和需要查找的参数元素的相等性。
请注意,Streams还使用equals()方法来检查对象相等性。
Check array contains elementString[] fruits = new String[] { "banana", "guava", "apple", "cheeku" }; boolean result = Arrays.asList(fruits) .stream() .anyMatch(x -> x.equalsIgnoreCase("apple")); //true boolean result = Arrays.asList(fruits) .stream() .anyMatch(x -> x.equalsIgnoreCase("lion")); //false
3. 使用迭代
最后,我们始终可以使用for-each 循环迭代数组项,并检查该项是否存在于数组中。
int[] intArray = new int[]{1, 2, 3, 4, 5}; boolean found = false; int searchedValue = 2; for(int x : intArray){ if(x == searchedValue){ found = true; break; } }
如果我们使用对象类型,请确保将if 条件更改为匹配的相等检查。
String[] stringArray = new String[]{"A", "B", "C", "D", "E"}; boolean found = false; String searchedValue = "B"; for(String x : stringArray){ if(x.equals(searchedValue)){ found = true; break; } }
以上就是Java中检查数组是否包含某元素的全部内容。