List 获取前N条数据

1.使用for循环遍历

java 复制代码
    public static void main(String[] args) {
	   int limit = 5;
        List<Integer> oldList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7);
        List<Integer> newList = Lists.newArrayList();
        if (oldList.size() <= limit) {
            newList.addAll(oldList);
            return;
        }
        for (int i = 0; i < limit; i++) {
            newList.add(oldList.get(i))
        }
    }

2.使用Stream API

java 复制代码
    public static void main(String[] args) {
        int limit = 5;
        List<Integer> oldList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7);
        List<Integer> newList = new ArrayList<>(limit);

        if (oldList.size() <= limit) {
            newList.addAll(oldList);
            return;
        }
        newList = oldList.stream().limit(limit).collect(Collectors.toList());
    }

3.使用subList方法

java 复制代码
    public static void main(String[] args) {
        int limit = 5;
        List<Integer> oldList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7);
        List<Integer> newList = new ArrayList<>(limit);

        if (oldList.size() <= limit) {
            newList.addAll(oldList);
            return;
        }
        newList = oldList.subList(0,limit);
    }

4.使用Apache Commons Collections

java 复制代码
    public static void main(String[] args) {
        int limit = 5;
        List<Integer> oldList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7);
        List<Integer> newList = new ArrayList<>(limit);

        if (oldList.size() <= limit) {
            newList.addAll(oldList);
            return;
        }
        CollectionUtils.addAll(newList, oldList.iterator());
    }
相关推荐
零叹1 小时前
篇章十 数据结构——排序
java·数据结构·算法·排序算法
朝朝又沐沐2 小时前
算法竞赛阶段二-数据结构(32)数据结构简单介绍
数据结构·算法
梦境虽美,却不长2 小时前
数据结构 (树) 学习 2025年6月12日12:59:39
数据结构·学习·二叉树·霍夫曼树·非二叉树
共享家95272 小时前
c语言(重点)
c语言·数据结构·算法
玉米的玉*」*2 小时前
【每日likou】704. 二分查找 27. 移除元素 977.有序数组的平方
数据结构·算法·leetcode
lyh13448 小时前
在macOS上运行Linux容器的方法
数据结构·状态模式
Roam-G8 小时前
List ToMap优化优化再优化到极致
java·list
1白天的黑夜19 小时前
二叉树-226.翻转链表-力扣(LeetCode)
数据结构·c++·leetcode
黑听人10 小时前
【力扣 中等 C++】90. 子集 II
开发语言·数据结构·c++·算法·leetcode
黑听人10 小时前
【力扣 简单 C】21. 合并两个有序链表
c语言·开发语言·数据结构·算法·leetcode