Is there a method to do the following without doing both methods: find
and map
?
val l = 0 to 3 l.find(_ * 33 % 2 == 0).map(_ * 33) // returns Some(66)
To convert a list into a map in Scala, we use the toMap method. We must remember that a map contains a pair of values, i.e., key-value pair, whereas a list contains only single values. So we have two ways to do so: Using the zipWithIndex method to add indices as the keys to the list.
Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. Maps are also called Hash tables. There are two kinds of Maps, the immutable and the mutable.
How about using collect?
// Returns List(66) List(1, 2, 3) collect { case i if (i * 33 % 2 == 0) => i * 33 }
However that will return all matches and not just the first one.
The better answer would have been, based on Scala 2.9:
// Returns Some(66) List(1, 2, 3) collectFirst { case i if (i * 33 % 2 == 0) => i * 33 }
The solution suggested in the comments to append a head
to get a Scala 2.8 version of that is not very efficient, I'm afraid. Perhaps in that case I would stick to your own code. In any case, in order to make sure it returns an option, you should not call head
, but headOption
.
// Returns Some(66) List(1, 2, 3) collect { case i if (i * 33 % 2 == 0) => i * 33 } headOption
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