What method truncates a list--for example to the first 100 elements--discarding the others (without iterating through individual elements)?
3 Answers
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.
-
2while 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) Aug 15, 2009 at 6:50
-
1If Java 8 is an option, I think
Stream.limit
should do the trick (docs.oracle.com/javase/8/docs/api/java/util/stream/…) Jul 31, 2017 at 22:38
list.subList(100, list.size()).clear();
or:
list.subList(0, 100);
-
6The first option modifies the list while the second does not. It shoud be
list = list.subList(0, 100)
– nessa.gpApr 4, 2016 at 15:00 -
3Also note that
subList(100, list.size()).clear()
will only work if list has its clear method implemented, for example if you createlist
byList<String> list = Arrays.asList(someString.split(","));
clear() will throwUnsupportedOperationException
sincelist
will be an abstractList
.– GyuriOct 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();
– ArefeOct 1, 2018 at 5:16 -
2
-
1
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
.take(10)
method on Collections, which was sufficient for my case. (The other nice thing about.take
is that it won't throw anIndexOutOfBoundsException
if the list is less than 10 elements). Code:myList.take(10).joinToString("\n", postfix = "\n")
etc.