Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all elements from a List after a particular index

Tags:

java

Is there any convenient way in List/ArrayList by which we can remove all elements of a List after a particular index. Instead of manually looping through it for removing.

To be more explanatory, if I have a list of 10 elements, I want to mention index 3 and then all elements after index 3 gets removed and my list would consist of only starting 4 elements now (counts from 0)

like image 710
Abhi Avatar asked Apr 02 '14 05:04

Abhi


People also ask

How do you remove the item at a given index from a list in Python?

The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.

How do I remove a specific index from a list in Java?

The remove(int index) method of List interface in Java is used to remove an element from the specified index from a List container and returns the element after removing it. It also shifts the elements after the removed element by 1 position to the left in the List.

How do you remove an element from an ArrayList at a specific index?

The remove(int index) method present in java. util. ArrayList class removes the element at the specified position in this list and shifts any subsequent elements to the left (i.e. subtracts one from their indices).


2 Answers

list.subList(4, list.size()).clear(); 

Sublist operations are reflected in the original list, so this clears everything from index 4 inclusive to list.size() exclusive, a.k.a. everything after index 3. Range removal is specifically used as an example in the documentation:

This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list:

     list.subList(from, to).clear(); 
like image 147
user2357112 supports Monica Avatar answered Oct 07 '22 04:10

user2357112 supports Monica


Using sublist() and clear(),

public class Count {     public static void main(String[] args)     {         ArrayList<String> arrayList = new ArrayList<String>();         arrayList.add("1");         arrayList.add("2");         arrayList.add("3");         arrayList.add("4");         arrayList.add("5");         arrayList.subList(2, arrayList.size()).clear();         System.out.println(arrayList.size());     } } 
like image 41
AJJ Avatar answered Oct 07 '22 05:10

AJJ