Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Lists of lists of integers

Tags:

list

scala

I am new to Scala and am a bit confused.

Given a list of lists List[List[Int]], how can one call a specific index of an element of each list, for example the second element of each list?

like image 271
tas Avatar asked Jan 27 '26 02:01

tas


2 Answers

Simple:

val ints = List( List(1,2), List(3,4) )
val result = ints.map( l => l(1) )

This will produce (2,4).

like image 91
Maurício Linhares Avatar answered Jan 29 '26 16:01

Maurício Linhares


While both of the other answers work, here is another version that is both safe to use and not complex. You can lift a Seq to a Function[Int, Option[A]] to make apply return Options instead of throwing exceptions. In Addition you can use flatMap instead of map{...}.flatten

List(List(1), List(1,2), List(1,2,3)).flatMap { xs =>
  xs.lift(1)
}

// res1: List[Int] = List(2, 2)
like image 36
drexin Avatar answered Jan 29 '26 14:01

drexin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!