Remove all elements from a List after a particular index

Java

Java Problem Overview


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)

Java Solutions


Solution 1 - Java

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();

Solution 2 - Java

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());
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAbhinavView Question on Stackoverflow
Solution 1 - Javauser2357112View Answer on Stackoverflow
Solution 2 - JavaAJJView Answer on Stackoverflow