Sidhant
Sidhant

Reputation: 441

Pop Last element from a list Scala

I'm trying to find the most efficient way to pop an element from a List[Map[String, String]] in scala.

What I want is something like this:

val last = myList.pop

Here last should have the last element and myList should have everything but last.

I can do this in two operations using last and init but that would require two linear operations. How can i avoid this?

Upvotes: 4

Views: 3387

Answers (2)

maasg
maasg

Reputation: 37435

An efficient way to pop the last element of a list, while preserving the rest of the elements is to reverse the list:

val last::rest = list.reverse

This has the effect of leaving the rest of the list in reverse, so the next pop is:

val last2 :: rest2 = rest

So "pop"-ing all the other elements of the list is cheap O(1). Note that this operation will fail if the list is empty, so it will need to be guarded accordingly.

That said, depending of the usecase, it might be better to consider other data structures. The classic FILO structure is a Stack. Indexable structures such as Arrays can also be a base for an implementation.

Upvotes: 3

Sivaram Kappaganthu
Sivaram Kappaganthu

Reputation: 53

we can use takeRight funtion that works the same way take works, but starts at the end of the sequence and moves forward, taking the specified number of elements from the end of the sequence:

val last = mylist.takeRight(1) 

This statement will give you the last element.

Upvotes: -1

Related Questions