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
Post a Comment