Java 将列表截断为给定数量的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1279476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Truncate a list to a given number of elements
提问by Sam
What method truncates a list--for example to the first 100 elements--discarding the others (without iterating through individual elements)?
什么方法会截断列表——例如截断前 100 个元素——丢弃其他元素(不遍历单个元素)?
采纳答案by Ben Lings
Use List.subList
:
使用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
:
您应该记住它subList
返回项目的视图,因此如果您希望列表的其余部分有资格进行垃圾回收,您应该将您想要的项目复制到一个新的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.
最后,请注意第二个参数应该比最后一个所需的索引多一个。
回答by karim79
list.subList(100, list.size()).clear();
or:
或者:
list.subList(0, 100);
回答by Ousmane D.
subList
, as suggested in the other answers, is the first that comes to mind. I would also suggest a stream approach.
subList
,正如其他答案中所建议的那样,是第一个想到的。我还建议采用流方法。
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