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.
max(): gives the largest element in the tuple as an output. Hence, the name is max().
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With