Make42 - 1 year ago 93
Scala Question

# Reduce by inspecting tuple element

I want to find the Tuple with the largest second element:

``````mylist.reduce { (x, y) => {
if (y._1 > x._1) y
else x
}}
``````

where
`x`
and
`y`
are of type
`Tuple3[DenseVector[Int], Double, PipelineModel]`
.

1) However, I get the error that
`>`
cannot be resolved. What's up with that? Using foldLeft and providing a zero element did not help either.

2) Can I write the code nicer? (It doesn't look so nice, I think.)

In a triplet (a, b, c) `triplet._2` gives you the second element.

`_1` gives first element

`_2` gives second element

`_3` gives third element

Tuples are not zero based.

``````scala> val triplet = (1, 2, 3)
triplet: (Int, Int, Int) = (1,2,3)

scala> triplet._1
res0: Int = 1

scala> triplet._2
res1: Int = 2

scala> triplet._3
res2: Int = 3
``````

In your case `triplet._1` gives the first element of the triplet (tuple3) which is `DenseVector[Int]` element on which you cannot use `>`. Thats why `>` is not resolved.

### maxBy

``````l.maxBy(_._2)
``````

Scala REPL

``````scala> val l = List((1, 2, 3), (0, 0, 1))
l: List[(Int, Int, Int)] = List((1,2,3), (0,0,1))

scala> l.maxBy(_._2)
res1: (Int, Int, Int) = (1,2,3)
``````

### Reduce

``````l.reduce { (x, y) =>  if (x._2 > y._2) x else y }
``````

Scala REPL

``````scala> val l = List((1, 2, 3), (0, 0, 1))
l: List[(Int, Int, Int)] = List((1,2,3), (0,0,1))

scala> l.reduce { (x, y) =>  if (x._2 > y._2) x else y }
res3: (Int, Int, Int) = (1,2,3)
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download