How to add an element to List while making sure that list contains latest n elements in scala -


in scala, best way add element list while making sure list contains latest n elements.

so if list (1, 2, 3, 4, 5) , n = 5, adding 6 should result in (2, 3, 4, 5, 6).

one possible way be:

list = list ::: list(6) list = list.takeright(5) 

are there better ways? also, there better data-structure maintaining such changing collection?

it sounds fixed size circular buffer satisfy need. think apache commons provides implementation.

a solution in scala using list be:

scala> def dropheadandaddtolist[t](obj: t, list: list[t]):list[t] = {           list.drop(1) :+ obj        }         dropheadandaddtolist: [t](obj: t, list: list[t])list[t]  scala> val = list(1,2,3,4,5) a: list[int] = list(1, 2, 3, 4, 5)  scala> dropheadandaddtolist(6, a) res0: list[int] = list(2, 3, 4, 5, 6) 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -