Home > OS >  Scala - finding a specific key in an array of tuples
Scala - finding a specific key in an array of tuples

Time:11-13

So far I have an array of tuples that is filled with key,value pairs (keys are ints and values are strings).

val tuple_array = new Array[(K,V)](100)

I want to find a specific key in this array. So far I have tried:

tuple_array.find()

but this requires me to enter a key,value pair. (I think). I want to just search this array and see if the key exists at all and if it does either return 1 or true.(havent decided yet). I could just loop through the array but I was going for a faster runtime.

How would I go about searching for this?

CodePudding user response:

find requires you to pass a predicate: function returning true if condition is fulfilled. You can use it e.g. like this:

tuple_array.find { tuple =>
  tuple._1 == searched_key
}

It doesn't require you to pass a tuple.

Since this is an array, you have to go through a whole array at worse case (O(n)), there is no faster way (asymptotically) unless your array is sorted and allows usage of a binary-search (which isn't a part of the interface as you never knows if a random array is sorted). Whether you'll do this by iterating manually or through find (or collectFirst) doesn't affect the speed much.

CodePudding user response:

but this requires me to enter a key,value pair. (I think).

No it doesn't, check the docs, you can just do:

tuple_array.find(_._1 == theKeyYouWant).map(_._2)

That returns an Option[V] with the value associated with the key if it was present. You then may just do an isDefined to return true if the key existed.

could just loop through the array but I was going for a faster runtime.

Well find just loops.

You may want to use a Map[K, V] instead of an Array[(K, V)] and just use contains


Also, as personal advice, it seems you are pretty new to the language; I would recommend you to pick a course or tutorial. Scala is way more than syntax.

  • Related