You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java创建foreach循环?批量生成1980-2014年份列表求助

生成1980-2014年份列表的实现方案

首先明确:foreach循环是用来遍历已有集合/序列的,没法直接生成连续数值序列。要生成1980到2014的年份并添加到List,推荐以下几种实用写法:

1. 基础for循环(最直观)

这是最容易理解的实现方式,直接循环生成每个年份并添加:

List<Integer> yearList = new ArrayList<>();
// 循环包含1980和2014,所以条件设为i <= 2014
for (int i = 1980; i <= 2014; i++) {
    yearList.add(i);
}

2. Java 8+ Stream API(更简洁)

如果使用Java 8及以上版本,用Stream API可以一行完成:

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

// ...

List<Integer> yearList = IntStream.rangeClosed(1980, 2014)
                                  .boxed() // 将int包装为Integer类型
                                  .collect(Collectors.toList());

3. 基于foreach的写法(不推荐)

如果一定要用foreach语法,需要先把年份范围转成可遍历序列,再遍历添加:

List<Integer> yearList = new ArrayList<>();
IntStream.rangeClosed(1980, 2014)
         .boxed()
         .forEach(year -> yearList.add(year));

这种写法本质还是依赖Stream生成序列,不如直接用Stream收集成List高效。

内容的提问来源于stack exchange,提问作者Adam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:30:57