在Java中,可以通过多种方式实现List的定长截取操作,以下是几种常见方法:
1、使用subList方法
subList(int fromIndex, int toIndex)是List接口提供的方法,可以从原List中截取指定范围的子列表。该方法遵循左闭右开原则,包含起始索引元素但不包含结束索引元素。
示例代码:
List<Integer> originalList = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> subList = originalList.subList(1, 4); // 获取索引1到3的元素
2、批量处理大数据量
当需要处理大量数据时(如几十万条记录),可以采用分批次处理的方式。通过循环每次截取固定长度(如100条)的子列表进行处理。
示例代码:
for (int i = 0; i < bigList.size(); i += batchSize) {
int end = Math.min(i + batchSize, bigList.size());
List<Object> batch = bigList.subList(i, end);
// 处理batch
}
3、创建固定长度List
如果需要创建固定长度的List,可以使用Arrays.asList()或Collections.nCopies()方法。
示例代码:
// 使用Arrays.asList创建固定长度List
List<String> fixedList = Arrays.asList(new String[5]);
// 使用Collections.nCopies创建带默认值的固定长度List
List<Integer> fixedListWithDefault = new ArrayList<>(Collections.nCopies(5, 0));
4、性能注意事项
- subList()返回的是原List的视图,对子列表的修改会影响原List
- 需要独立子列表时,建议使用new ArrayList<>(list.subList())创建新对象
- 在循环中直接调用list.size()不会造成明显性能损耗,因为该方法只是返回内部变量值