Make42 - 4 months ago 27

Scala Question

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`

`y`

`Tuple3[DenseVector[Int], Double, PipelineModel]`

1) However, I get the error that

`>`

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

Answer

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
```

**Answer 1:**

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.

**Answer 2:**

```
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)
```

```
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)
```