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?
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.
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.
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.
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 .
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.
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 }
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With