Hi, basically I'm not really a Java/Scala fan, but unfortunately I'm forced to use it for my studies. Anyways, I was given an assignment:
What the program gets is a list of objects like: Mark(val name String, val style_mark Int, val other_mark Int)
.
How can I use groupBy, to group the marks by name, and get an average for style_mark and other_mark?
Mark("John", 2, 5)
Mark("Peter", 3, 7)
Mark("John", 4, 3)
Should return:
Mark("John", 3, 4)
Mark("Peter", 3, 7)
Thats the code:
class Mark(val name: String, val style_mark: Int, val other_mark: Int) {}
object Test extends Application
{
val m1 = new Mark("Smith", 18, 16);
val m2 = new Mark("Cole", 14, 7);
val m3 = new Mark("James", 13, 15);
val m4 = new Mark("Jones", 14, 16);
val m5 = new Mark("Richardson", 20, 19);
val m6 = new Mark("James", 4, 18);
val marks = List(m1, m2, m3, m4, m5, m6);
def avg(xs: List[Int]) = xs.sum / xs.length
marks.groupBy(_.name).map { kv => Mark(kv._1, avg(kv._2.map(_.style_mark)), avg(kv._2.map(_.other_mark))) }
println(marks);
}
Any help would be greatly appreciated,
Paul