Reputation: 81
Scala accessing list objects and evaluating them
I have list
val example = List(ItemDesc(6164,6165,6166,6195,The values are correct), ItemDesc(14879,14879,14879,14894,The values are ok), ItemDesc(19682,19690,19682,19694,The values are good))
From the example List, I want to access object 'ItemDesc'. And get the even count and odd count.
For example, taking the first object in the list
ItemDesc(6164,6165,6165,6195,The values are correct)
I want to find out,
evenPlacesCount = 6164+6166
oddPlacesCount = 6165+6195
I have the code to evaluate if it is a plain List(6164,6165,6166,6195,The values are correct).
But how compute if I have List objects like 'example' above ?
Upvotes: 2
Views: 56
Reputation: 9698
Something like this?
case class ItemDesc(a: Int, b: Int, c: Int, d: Int, desc: String)
case class Pair(even: Int, odd: Int)
val example = List(
ItemDesc(6164, 6165, 6166, 6195, "The values are correct"),
ItemDesc(14879, 14879, 14879, 14894, "The values are ok"),
ItemDesc(19682, 19690, 19682, 19694, "The values are good")
)
def evenOddCount(item: ItemDesc): Pair = Pair(item.a + item.c, item.b + item.d)
def addEvenOddCounts(first: Pair, second: Pair): Pair = Pair((first.even + second.even), (first.odd + second.odd))
val evenOddPair = evenOddCount(ItemDesc(6164, 6165, 6166, 6195, "The values are correct")) // Pair(12330,12360)
val allPairs = example.map(evenOddCount) // List(Pair(12330,12360), Pair(29758,29773), Pair(39364,39384))
val totalPair = example.map(evenOddCount).reduce(addEvenOddCounts) // Pair(81452,81517)
Upvotes: 2