Duzzz
Duzzz

Reputation: 191

Filtering a sequence based on item length

I have this seq users that has lots of strings. What I want to do is to filter the seq based on word length. This can be done by saying filtered_users = users.filter(_.length == x) (x = wanted word length)

However, I would like to add to the filtered list are a char longer and char shorter words. I have done it by manually writing

filtered_users2 = users.filter(_.length == x+1) 
filtered_users3 = users.filter(_.length == x-1)
filtered_users ++= (filtered_users1 ++ filtered_users2)

I might need 2 chars longer/shorter added to the seq as well so what I am looking for is a method to go through the users and filter out all that are too long or too short names. I created this using for loop

var filter = Seq[String]()
for (i <- max(0, x - difference) to (x + difference)) {
filter ++= users.filter(_.length == i)
} 

where word length x and difference are given beforehand. However, if the seq is long, I wouldn't want to ge through it too many times. What I am seeking is a implementation that goes through the user seq only once and returns the filtered list.

Obviously,

val filtered_users = users.filter(_.length == x || _.length == x - 1 || _.length == x + 1)

didn't work.

Upvotes: 0

Views: 1402

Answers (1)

Tzach Zohar
Tzach Zohar

Reputation: 37842

If you use _ more than once in an anonymous function, it is treated as multiple input arguments (the first _ would be the first argument, the second would be the second argument and so on). If you want to use an argument more than once, you'll have to name it:

val x = 3
val difference = 1

users.filter(u => u.length >= x - difference && u.length <= x + difference)

Upvotes: 1

Related Questions