Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a matching element in a list and map it in as an Scala API method?

Tags:

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) 
like image 438
agilefall Avatar asked Mar 29 '11 21:03

agilefall


People also ask

How do I convert a list to map in Scala?

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.

What is .map in Scala?

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.


1 Answers

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 
like image 168
Wilfred Springer Avatar answered Nov 20 '22 21:11

Wilfred Springer