Remove all elements from a List after a particular index

Abhi :

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)

user2357112 supports Monica :
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();

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Remove all elements from a list after a particular value

Remove multiple elements from a list of index with Python

Remove elements from a List at a specific index

Remove duplicates from a list and remove elements at same index in another list

How to remove all the elements of list from a string?

Remove characters from a string in all elements of a list

Remove all elements except string from list

Extract same elements chunk from list after instance of a particular element

XSLT script to remove elements after a particular element

How to make a function to remove elements by index from a list

Prolog remove elements which have the same value as the index from the list

Get List of all elements of a particular type

Remove elements from array except particular one

Remove all the rows after an index value from an array in Fortran

How do I remove all List elements from an Array?

How to remove all elements that doesn't meet requirements from list

How to remove from list all successive equal elements?

Scala - Remove all elements in a list/map of strings from a single String

Remove an item from a list by shifting all other elements

Remove all items after an index

Python delete all elements from a list that are on an odd index

How to fetch very particular elements from a list?

Remove particular similar element from the list in python

inserting all the elements from a list into specific index of sublist from a second list - python 2

Remove elements from a Linked List

Remove duplicated elements from list

Remove multiple elements from a List

Remove elements from python list

Remove elements from a list C