Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an item from a list in Scala having only its index?

Tags:

I have a list as follows:

val internalIdList: List[Int] = List()  internalIdList = List(11, 12, 13, 14, 15) 

From this list would remove the third element in order to obtain:

internalIdList = List(11, 12, 14, 15) 

I can not use a ListBuffer, are obliged to maintain the existing structure. How can I do?

Thanks to all

like image 917
YoBre Avatar asked Sep 17 '13 10:09

YoBre


People also ask

How do you remove an item from a list using its index?

There are two options to remove an element by its index in list. Using del statement, and using pop() method. The del statement needs index of the element to remove. The pop() method of built-in list class requires index as argument.

How do you delete a specific index?

You can use the splice() method to remove the item from an array at specific index in JavaScript. The syntax for removing array elements can be given with splice(startIndex, deleteCount) .

How do you get the index of an element in a list in Scala?

Scala List indexOf() method with example. The indexOf() method is utilized to check the index of the element from the stated list present in the method as argument. Return Type: It returns the index of the element present in the argument.


1 Answers

There is a .patch method on Seq, so in order to remove the third element you could simply do this:

List(11, 12, 13, 14, 15).patch(2, Nil, 1) 

Which says: Starting at index 2, please remove 1 element, and replace it with Nil.

Knowing this method in depth enables you to do so much more than that. You can swap out any sublist of a list with arbitrary other.

like image 177
Rok Kralj Avatar answered Dec 16 '22 10:12

Rok Kralj