0

I have a list of tuples like below

List((a,1), (a,2), (b,2), (b,1)) 

I want to create a List like below from that above list

List((a,2), (b,2))

Only one first element and MAX of the second element. How can I do this concisely?

4
  • 1
    Trying this list.groupBy(._1).map { case (common, lst) => (common, lst.reduce( max _)) } Commented Aug 29, 2017 at 23:29
  • So, what problems did you encounter when you tried it? Commented Aug 29, 2017 at 23:32
  • @Dima Pressed return before I entered my full comment. This is what I am getting when I tried error: value max is not a member of (String, Int) Commented Aug 29, 2017 at 23:37
  • This worked myList.groupBy(._1).map {case (common, lst) => lst.maxBy(._2) }.toList Commented Aug 29, 2017 at 23:51

1 Answer 1

1

Since you only need the 1st elements of same value once along with the max value of the corresponding 2nd element, it's no difference from rephrasing the question as for every distinct 1st element in the tuple list, list the max 2nd element:

val l = List(("a",1), ("a",2), ("b",2), ("b",1))

l.groupBy(_._1).
  mapValues( _.map(_._2).max ).
  toList
// res1: List[(String, Int)] = List((b,2), (a,2))
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Even better.

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.