Truncate a list to a given number of elements

JavaCollections

Java Problem Overview


What method truncates a list--for example to the first 100 elements--discarding the others (without iterating through individual elements)?

Java Solutions


Solution 1 - Java

Use List.subList:

import java.util.*;
import static java.lang.Math.min;

public class T {
  public static void main( String args[] ) {
    List<String> items = Arrays.asList("1");
    List<String> subItems = items.subList(0, min(items.size(), 2));

    // Output: [1]
    System.out.println( subItems );

    items = Arrays.asList("1", "2", "3");
    subItems = items.subList(0, min(items.size(), 2));

    // Output: [1, 2]
    System.out.println( subItems );
  }
}

You should bear in mind that subList returns a view of the items, so if you want the rest of the list to be eligible for garbage collection, you should copy the items you want to a new List:

List<String> subItems = new ArrayList<String>(items.subList(0, 2));

If the list is shorter than the specified size, expect an out of bounds exception. Choose the minimum value of the desired size and the current size of the list as the ending index.

Lastly, note that the second argument should be one more than the last desired index.

Solution 2 - Java

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

or:

list.subList(0, 100);

Solution 3 - Java

subList, as suggested in the other answers, is the first that comes to mind. I would also suggest a stream approach.

source.stream().limit(10).collect(Collectors.toList()); // truncate to first 10 elements
source.stream().skip(2).limit(5).collect(Collectors.toList()); // discards the first 2 elements and takes the next 5

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
QuestionSamView Question on Stackoverflow
Solution 1 - JavaBen LingsView Answer on Stackoverflow
Solution 2 - Javakarim79View Answer on Stackoverflow
Solution 3 - JavaOusmane D.View Answer on Stackoverflow