139

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

1
  • I found this question while looking for a way to trim a list to the first 10 elements in Kotlin lol. It turns out Kotlin defines the .take(10) method on Collections, which was sufficient for my case. (The other nice thing about .take is that it won't throw an IndexOutOfBoundsException if the list is less than 10 elements). Code: myList.take(10).joinToString("\n", postfix = "\n") etc.
    – takanuva15
    Oct 17 at 3:00

3 Answers 3

157

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.

4
  • 2
    while the question is not exactly clear, it does sound like sam wants a the end of the list deleted. Therefore your answer should include a list.clear().
    – mP.
    Aug 14, 2009 at 23:15
  • This is not likely to perform as well as karim79's solution, which is the best alternative - it has the best chance of performing well and is the cleanest code as well. Aug 15, 2009 at 5:08
  • I think it depends on the number of elements to be removed (and also if the List supports modification)
    – Ben Lings
    Aug 15, 2009 at 6:50
  • 1
    If Java 8 is an option, I think Stream.limit should do the trick (docs.oracle.com/javase/8/docs/api/java/util/stream/…)
    – Eran Medan
    Jul 31, 2017 at 22:38
61
list.subList(100, list.size()).clear();

or:

list.subList(0, 100);
6
  • 6
    The first option modifies the list while the second does not. It shoud be list = list.subList(0, 100)
    – nessa.gp
    Apr 4, 2016 at 15:00
  • 3
    Also note that subList(100, list.size()).clear() will only work if list has its clear method implemented, for example if you create list by List<String> list = Arrays.asList(someString.split(",")); clear() will throw UnsupportedOperationException since list will be an abstract List.
    – Gyuri
    Oct 14, 2016 at 18:16
  • If you would like to keep the initial n elements of the List, it should be list.subList(n, list.size()).clear();
    – Arefe
    Oct 1, 2018 at 5:16
  • 2
    Shame you have to create an object just to shorten a list Oct 24, 2018 at 20:13
  • 1
    @DavidBradley True but HotSpot may actually optimize this away Nov 8, 2019 at 0:01
21

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.