LXSoft
LXSoft

Reputation: 596

How to create list of objects from tuples, then select object by smallest attribute?

As question in my title, how to create a list of objects from a list of tuples, then select minimum from that list of object by smallest attribute to return it's index.

I have a list of tuples, for which I have created two case classes:

case class Animal(typeA: String, name: String, months: Int)
case class Animals(animals: List[Animal])

List((Hero, Dog, 8), (Ninja, Cat, 17), (Kitty, Cat, 12), (Snoop, Lion, 3) ... )

How can I convert this list to desired output:

Animals(Animal(Hero, Dog, 8), Animal(Ninja, Cat, 17), Animal(Kitty, Cat, 12), Animal(Snoop, Lion, 3) ... )

I can do it easly by parsing a JSON file, and using a flatMap, with asOpt method, which will convert my tuple to animals:

animals = feature._1.properties.flatMap(_.asOpt[Animals])

But as I have described above is with using JSON parsing, my tuples are in a list, so I tried this without success:

val raw_Animals = List((Hero, Dog, 8), (Ninja, Cat, 17), (Kitty, Cat, 12), (Snoop, Lion, 3) ... )
var animals : Animals[List[Animal]] = raw_Animals.flatMap(_.asOpt[Animal])
val ages = animals.map(animal => animal._3.toInt).toList
val minAge = ages.min
val index = animals.indexWhere(_._3 == minAge)
println(animals(index))

I appreciate any method.

Upvotes: 0

Views: 147

Answers (2)

Karl
Karl

Reputation: 1230

I feel like your Animals wrapper for your List[Animal] is a bit unnecessary, since you have to call .animals to get the underlying collection, but this should accomplish what you want. You can leverage the Function3.tupled function to get your tuples mapped to Animal and Collections minBy function to find the smallest by age:

scala>   val raw_Animals = List(("Hero", "Dog", 8), ("Ninja", "Cat", 17), ("Kitty", "Cat", 12), ("Snoop", "Lion", 3))
raw_Animals: List[(String, String, Int)] = List((Hero,Dog,8), (Ninja,Cat,17), (Kitty,Cat,12), (Snoop,Lion,3))

scala>   val animals = Animals(raw_Animals.map(Animal.tupled))
animals: Animals = Animals(List(Animal(Hero,Dog,8), Animal(Ninja,Cat,17), Animal(Kitty,Cat,12), Animal(Snoop,Lion,3)))

scala>   val ages = animals.animals.map(_.months)
ages: List[Int] = List(8, 17, 12, 3)

scala>   val minAgeAnimal = animals.animals.minBy(_.months)
minAgeAnimal: Animal = Animal(Snoop,Lion,3)

scala>   println(minAgeAnimal)
Animal(Snoop,Lion,3)

Upvotes: 4

bjfletcher
bjfletcher

Reputation: 11518

You can use .tupled like so:

case class Animal(typeA: String, name: String, months: Int)
case class Animals(animals: List[Animal])
val raw_Animals = List(("Hero", "Dog", 8), ("Ninja", "Cat", 17))

Animals.tupled(raw_Animals.map(Animal.tupled))
// -> Animals(List(Animal(Hero,Dog,8), Animal(Ninja,Cat,17)))

Upvotes: 1

Related Questions