Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore None values when I map over a collection

Tags:

scala

I have the following code:

for {
  totalUsers = currentUsers.map { u =>
    newUsersMap.get(u.username.get).map { t =>
      FullUser(t.username, u.firstName, u.lastName, u.batch, t.description)
    }
  }
} yield {
  totalUsers
}

This is returning a Seq[Option[FullUser]] when what I want is a Seq[FullUser] - i.e. if that call to u.username.get returns None, then just ignore it. How do I do this?

like image 925
jcm Avatar asked Sep 20 '25 03:09

jcm


2 Answers

Consider flatmapping.

val totalUsers = currentUsers.flatMap { u =>
  newUsersMap.get(u.username.get).map { t =>
    FullUser(t.username, u.firstName, u.lastName, u.batch, t.description)
  }
}

For some explanation how Seq, Option, and flatMap work together, see for example this blog post.

like image 175
0__ Avatar answered Sep 23 '25 07:09

0__


Just try for comprehension

for {
  user <- currentUsers
  username <- user.username.toList      //you need to convert to seq type to prevent ambiguous option seq mix problems.
  t <- newUserMap.get(username).toList
} yield FullUser(t.username, u.firstName, u.lastName, u.batch, t.description)

for mix with flatMap or map is not readable.

like image 36
tiran Avatar answered Sep 23 '25 05:09

tiran