How to ignore None values ​​when matching a collection

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 returns Seq[Option[FullUser]]

when I want Seq[FullUser]

- that is, if this call u.username.get

returns None, then just ignore it. How to do it?

+3


source to share


2 answers


Consider a flat mapping.

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 of how Seq

, Option

and flatMap

work together, see, for example, this blog post .

+5


source


Just try to understand.

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)

      



to mix with flatMap

or map

not read.

+4


source







All Articles