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

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

问题描述

什么方法截断列表 - 例如前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 返回项目的视图,所以如果你想让列表的其余部分有资格进行垃圾收集,你应该将你想要的项目复制到一个新的 List

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天全站免登陆