将列表截断为给定数量的元素 [英] Truncate a list to a given number of elements

查看:26
本文介绍了将列表截断为给定数量的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么方法会截断列表——例如截断前 100 个元素——丢弃其他元素(不遍历单个元素)?

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

推荐答案

使用 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 );
  }
}

您应该记住 subList 返回项目的视图,因此如果您希望列表的其余部分有资格进行垃圾回收,您应该将您想要的项目复制到一个新的列表:

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.

这篇关于将列表截断为给定数量的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆