Scala : List examples

HI,

 

In below blog will give some examples of scala list basic programs

object listq extends App {

//1 .Find the last element of a list.
var a = List(1, 2, 3, 2, 1)

def listlast(a:List[Int]):Int=
{
val res=a.last.toInt
return res

}
// Find the second last element of list
def secondlast(a:List[Int]):Int=
{
val res = a(a.length-2)
return res

}

//find n’th element of list
def kelement(a:List[Int],n:Int):Int=
{
val res = a(n-1)
return res
}
println(listlast(a),secondlast(a),kelement(a,1))
println(a.length)
print(a.reverse)

// find list is pallindrome or not
def ispallindrome(a:List[Int]):Boolean=
{
if(a.reverse==a)
{
return true
}
else
{
return false
}
}

// remove consecutive duplicates in list and print
def removeduplicates(a:List[String])
{ var temp=”z”
var last=”0″
for(i<-0 to a.length-2)
{
if(a(i)==a(i+1))
{
temp=a(i)

}

else
{temp=a(i)
print(temp)
}

}
if (a(a.length-2)==a(a.length-1))
{
last=a(a.length-2)

}
println(last)
}
println(ispallindrome(a))
val aa=List(“a”, “a”, “a”, “a”, “b”, “c”, “c”, “a”, “a”, “d”, “e”, “e”, “e”, “e”)
removeduplicates(aa)
}

 

 

please provide feedback and your comments

 

thanks

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s