Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find max in a list of tuples?

Tags:

scala

I have the following list of tuples:

val arr = List(('a',10),('b',2),('c',3))

How to find the tuple with the max key or max value?

The proper answer should be (c, 3) for max key lexicographically or ('a', 10) for max value.

like image 338
Shakti Avatar asked Apr 02 '13 16:04

Shakti


People also ask

Can we use Max in tuple?

max(): gives the largest element in the tuple as an output. Hence, the name is max().

How do you find a maximum value in a list?

Method 5: Use the max() and def functions to find the largest element in a given list. The max() function prints the largest element in the list.

What is maximum number of elements possible in tuple?

Given a tuple list with string and its magnitude, the task is to write a python program to join all the strings with maximum magnitudes. Explanation : 8 is maximum tuple element and concatenation of keys yield the result. Explanation : 8 is maximum tuple element and concatenation of keys yield the result.


2 Answers

Easy-peasy:

scala> val list = List(('a',10),('b',2),('c',3))
list: List[(Char, Int)] = List((a,10), (b,2), (c,3))

scala> val maxByKey = list.maxBy(_._1)
maxByKey: (Char, Int) = (c,3)

scala> val maxByVal = list.maxBy(_._2)
maxByVal: (Char, Int) = (a,10)

So basically you can provide to List[T] any function T => B (where B can be any ordered type, such as Int or String by example) that will be used to find the maximum.

like image 107
om-nom-nom Avatar answered Oct 26 '22 17:10

om-nom-nom


Starting in Scala 2.13, a slightly safer solution (which handles empty lists) would consist in using maxByOption/minByOption which returns None if the sequence is empty:

List(('a', 10),('b', 2),('c', 3)).maxByOption(_._1)
// Option[(Char, Int)] = Some((c,3))
List[(Char, Int)]().maxByOption(_._1)
// Option[(Char, Int)] = None

This way you could also decide to fallback on a default value when the list is empty:

List[(Char, Int)]().maxByOption(_._1).getOrElse(('a', 1))
// (Char, Int) = (a,1)
like image 26
Xavier Guihot Avatar answered Oct 26 '22 15:10

Xavier Guihot