In Kotlin, how to check, contains this or that meaning?

In Kotlin we can do:

val arr = intArrayOf(1,2,3) if (2 in arr) println("in list") 

But if I want to check if 2 or 3 are in arr , which is the most idiomatic way to do this, except:

 if (2 in arr || 3 in arr) println("in list") 
+7
arrays kotlin
source share
6 answers

I would use the any () method :

 arrayOf(1, 2, 3).any { it == 2 || it == 3 } 

This way you only go through the array once and you do not create an instance of set to check if it is empty or not (for example, in one of the other answers to this question).

+7
source share

You can use intersect , it takes iterability as a parameter and returns a collection containing only the elements that are in your collection as well as the iterability that you provided. Then on this set you just need to do a size check.

Here is an example:

 val array1 = arrayOf(1, 2, 3, 4, 5, 6) val array2 = arrayOf(2, 5) // true if array1 contains any of the items from array2 if(array1.intersect(array2.asIterable()).isNotEmpty()) { println("in list") } 
+6
source share

This is the shortest and most idiomatic way I can use any and in :

 val values = setOf(2, 3) val array = intArrayOf(1, 2, 3) array.any { it in values } 

Of course, you can use the link for the in operator :

 array.any(values::contains) 

I use setOf for the first collection because the order does not matter.

Edit: I switched values and array due to alex.dorokhow answer . Ordering doesn't matter for validation, but for performance.


OP wanted the most idiomatic way to solve this. If you go to the ada answer after a more efficient way. Sub>

+4
source share

Combining @aga and @ willi-mentzel solutions to increase efficiency and dynamically set validated values:

 val numbers = setOf(2, 3) arrayOf(1, 2, 3).any(numbers::contains) 

In this case, the array will be iterated completely only once (at most, in the worst case).

This is more efficient than (suggested by @WilliMentzel):

 numbers.any(arrayOf(1, 2, 3)::contains) // don't do that! 

If in the worst case, the array will repeat set.count .

Note that Set.contains has O (1) complexity, but IntArray :: contains has O (N).

Of course, this optimization makes sense only if the collection or array is large enough.

+3
source share

I think the most readable way to write a statement is the opposite:

 val arr = intArrayOf(1,2,3) val match = setOf(2, 3).any(arr::contains) 

In some scenarios, it is possible to use ranges:

 val match = (2..3).any(arr::contains) 

In the end, your solution looks pretty good to me already. Although they do not use the functionality of the library.

+2
source share

If it doesn't matter if both occur in an array, you can use the when statement as follows:

 when (arr) { 2,3 --> println("in list") else --> println("not in list") } 

This will print β€œin list” if in list 2 or 3.

For more information on flow control, see here .

-2
source share

All Articles