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());
    }
相关推荐
Luna-player6 分钟前
在前端中list.map的用法
前端·数据结构·list
历程里程碑23 分钟前
C++ 10 模板进阶:参数特化与分离编译解析
c语言·开发语言·数据结构·c++·算法
Byron Loong28 分钟前
【Python】字典(dict)、列表(list)、元组(tuple)
开发语言·python·list
晨曦夜月2 小时前
笔试强训day5
数据结构·算法
H_z___2 小时前
Hz的计数问题总结
数据结构·算法
练习时长一年2 小时前
LeetCode热题100(搜索插入位置)
数据结构·算法·leetcode
凌睿马2 小时前
关于复杂数据结构从MySQL迁移到PostgreSQL的可行性
数据结构·数据库·mysql
Fine姐3 小时前
数据结构03——树
数据结构
gugugu.3 小时前
Redis List类型完全指南:从原理到实战应用
数据库·redis·list
ChoSeitaku3 小时前
NO17数据结构选择题考点|图
数据结构