0

For example list is:

case class User(s: String, value: Int)
case class Name(i: Int, users: List[User])

List(Name(1, List(User("A", 1000), User("B", 500))), Name(2, List(User("A", 800),   User("B", 420))))

Then how to get output using scala: (wanna to add the values: for ex: 1000+ 500 and 800+420)

How to get result in sorted order by value.

3
  • show your case class implementation Commented Aug 11, 2015 at 11:24
  • you can't get such result because Name(1, 1500) and Name(1, List(User(A, 1000), User(B, 500))) has different classes definitions but same names. You can't have 2 classes in a package with the same name. Commented Aug 11, 2015 at 11:27
  • any result that should be only sum of values: ex: 1000+ 500 and 800+420 Commented Aug 11, 2015 at 11:30

2 Answers 2

2

Assuming that you defined such classes:

case class User(s: String, value: Int)
case class Name(i: Int, users: List[User])

val list = List(Name(1, List(User("A", 1000), User("B", 500))), Name(2, List(User("A", 800), User("B", 420))))

val result = list.map(_.users.map(_.value).sum)
println(result)

You will get:

List(1500, 1220)
Sign up to request clarification or add additional context in comments.

Comments

1

You can solve your problem with

case class Name(number: Int, users: List[User])
case class User(name: String, number: Int)

val list = List(Name(1, List(User("A", 1000), User("B", 500))), Name(2, List(User("A", 800), User("B", 420))))

val result = list.map{
  name =>
    val sum = name.users.map {
      _.number
    }.sum
    (name.number, sum)
}

println(result) // List((1,1500), (2,1220))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.