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());
    }
相关推荐
zh_xuan42 分钟前
LeeCode 40.组合总和II
c语言·数据结构·算法
wangluoqi1 小时前
c++ 数据结构-并查集、ST表 小总结
数据结构·c++
小马学嵌入式~10 小时前
数据结构:队列 二叉树
c语言·开发语言·数据结构·算法
省四收割者12 小时前
Go语言入门(10)-数组
数据结构·经验分享·笔记·vscode·算法·golang
月盈缺14 小时前
学习嵌入式的第二十四天——数据结构——队列和树
数据结构·学习
iFlyCai18 小时前
鸿蒙开发中的List组件详解
华为·list·harmonyos
Y40900118 小时前
Java算法之排序
java·数据结构·笔记·算法
艾莉丝努力练剑20 小时前
【C语言16天强化训练】从基础入门到进阶:Day 6
c语言·数据结构·学习·算法
快去睡觉~21 小时前
力扣1005:k次取反后最大化的数组和
数据结构·算法·leetcode
想不明白的过度思考者21 小时前
初识数据结构——Map和Set:哈希表与二叉搜索树的魔法对决
数据结构·散列表