Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Check whether a value exist in an Array

Tags:

java

arrays

I have an array named "bob" which contains values.

String[] bob = { "this", "is", "a", "really", "silly", "list" }; 

How can I know whether "silly" value exists in the array named bob without iterating through it?

like image 728
user2065795 Avatar asked Feb 13 '13 17:02

user2065795


People also ask

How do you check if a value is in an array?

isArray(variableName) method to check if a variable is an array. The Array. isArray(variableName) returns true if the variableName is an array. Otherwise, it returns false .

How do you check a string is present in array or not?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.


2 Answers

You can use List#contains method. For that you need to convert your array to a list. You can use Arrays#asList() method fot that:

String[] bob = { "this", "is", "a", "really", "silly", "list" };  if (Arrays.asList(bob).contains("silly")) {     // true } 
like image 92
Rohit Jain Avatar answered Sep 22 '22 05:09

Rohit Jain


Convert the Array to List using static Arrays.asList(T) and check with List.contains(Object) to check if an object exists in the retuned collection.

    String[] bob = { "this", "is", "a", "really", "silly", "list" };            System.out.println(Arrays.asList(bob).contains("silly")); 

Traditional way however would be to iterate over the array and check at each element using equals().

like image 34
PermGenError Avatar answered Sep 24 '22 05:09

PermGenError