nitesh
nitesh

Reputation: 47

How do I find single attribute value in the list of objects in scala

I need to get the single attribute uuid and not Seq(UUID) from below class

case class Country(uuid: UUID, name: String, code:String)

val countries = Seq(
                  Country(20354d7a-e4fe-47af-8ff6-187bca92f3f9, "Afghanistan", "AFG"),
                  Country(caa8b54a-eb5e-4134-8ae2-a3946a428ec7,"Albania", "ALB"), 
                  Country(bd2cbad1-6ccf-48e3-bb92-bc9961bc011e, "Algeria", "DZA")
              )

val xyz: UUID = Country_uuid_from_countries

I tried val UUIDs = countries.map(_.uuid) but it returs Seq[UUID]

UUIDs: Seq[UUID] = List(20354d7a-e4fe-47af-8ff6-187bca92f3f9,
                           caa8b54a-eb5e-4134-8ae2-a3946a428ec7,
                           bd2cbad1-6ccf-48e3-bb92-bc9961bc011e
                   )

How do I just get UUID?

Upvotes: 0

Views: 828

Answers (1)

So you have a List of Countries, and a function (logic) for transforming one Country into AnotherCountry. And what you really want at the end is another List of AnotherCountries.

That is a well know problem. Every time you have a value A inside a context F[_] (a List is a context of multiplicity), and a function A => B. And you want to apply this transformation preserving the context to get an F[B] as a result. Then you can use def map[F[_], A, B](fa: F[A])(f: A => B): F[B].

In the case of Scala, is common that the context themselves provide these functions as methods.
So, the only thing you need to do is this:

final case class Country(uuid: UUID, name: String, code: String)
final case class AnotherCountry(uuid: UUID)

val countries = List(
  Country(20354d7a-e4fe-47af-8ff6-187bca92f3f9, "Afghanistan", "AFG"),
  Country(caa8b54a-eb5e-4134-8ae2-a3946a428ec7,"Albania", "ALB"), 
  Country(bd2cbad1-6ccf-48e3-bb92-bc9961bc011e, "Algeria", "DZA")
)

val anotherCountires = countries.map { country =>
  AnotherCountry(uuid = country.uuid)
}

Upvotes: 3

Related Questions