Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Idiomatic way to check array contains value

Tags:

arrays

kotlin

What's an idiomatic way to check if an array of strings contains a value in Kotlin? Just like ruby's #include?.

I thought about:

array.filter { it == "value" }.any()

Is there a better way?

like image 683
jturolla Avatar asked Feb 14 '17 19:02

jturolla


People also ask

How do I check if a value is in array Kotlin?

To check if an Array contains a specified element in Kotlin language, use Array. contains() method. Call contains() method on this array, and pass the specific search element as argument. contains() returns True if the calling array contains the specified element, or False otherwise.

How do you check if an array contains a certain value?

JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.

How do you check if a list contains an element in Kotlin?

To check if a specific element is present in this List, call contains() function on this List object and pass given element as argument to this function. The Kotlin List. contains() function checks if the list contains specified element and returns a boolean value.

How do I use contains in ArrayList Kotlin?

First, we create an empty ArrayList to store the strings. Next, we add a few company names to the ArrayList object, using the add() method such as: "Google" , "Apple" , "Microsoft" , and "Netflix" . Next, we call the contains() method by passing Microsoft as input and it returns true .


3 Answers

The equivalent you are looking for is the contains operator.

array.contains("value") 

Kotlin offer an alternative infix notation for this operator:

"value" in array

It's the same function called behind the scene, but since infix notation isn't found in Java we could say that in is the most idiomatic way.

like image 93
Geoffrey Marizy Avatar answered Oct 25 '22 20:10

Geoffrey Marizy


You could also check if the array contains an object with some specific field to compare with using any()

listOfObjects.any{ object -> object.fieldxyz == value_to_compare_here }
like image 23
Amar Jain Avatar answered Oct 25 '22 18:10

Amar Jain


Here is code where you can find specific field in ArrayList with objects. The answer of Amar Jain helped me:

listOfObjects.any{ it.field == "value"}
like image 40
Dimitar Avatar answered Oct 25 '22 20:10

Dimitar