![]() In a similar approach, I loop over the Map as shown next, creating a field named rating1 which I again don't use because I don't need it: (Which is why I don't like this approach for this instance.) In that approach, I ignore the second element of each Tuple, because I don't need it. If (ntains(movie._1)) similarItems += (movie._1 -> true) ![]() ![]() While I chose that looping method in my code, I could also use the “tuples” approach, where movie is a Tuple, and I only use the first element of the Tuple, which happens to be my keys: If (ntains(movie)) similarItems += (movie -> true) In my case, when I'm iterating over the Map I’m really just interested in the keys, so the cleanest way to loop over every Map element is like this: To begin with, I defined my Map like this: To demonstrate a more “real world” example of looping over a Scala Map, while working through some programming examples in the book, Programming Collective Intelligence, I decided to code them up in Scala, and I wanted to share the approaches I prefer using the Scala foreach and for loops. Scala is beginning to remind me of the Perl slogan: “There’s more than one way to do it,” and this is good, because you can choose whichever approach makes the most sense for the problem at hand. You can choose whatever format you prefer. For me, this is by far the easiest technique: Once you have a Map, you can iterate over it using several different techniques. Scala> val m1 = Map("fname" -> "Al", "lname" -> "Alexander") Iterating over Scala maps To get started with some examples, let’s create a simple Scala Map we can work with: There are several different ways to iterate over a Scala Map, and the method you choose depends on the problem you need to solve. Scala Map FAQ: How can I iterate/loop over a Scala Map? show more info on classes/objects in repl.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |