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());
    }
相关推荐
春弦_29 分钟前
自用算法整理二
数据结构·算法·图论
xxxiugou1236 小时前
链表算法题精讲:从两数相加到K组翻转
数据结构·c++·算法·链表
悠仁さん10 小时前
【算法C++】双指针(一)
数据结构·c++·算法
YukiRinLL10 小时前
字符串存储与 BF、KMP 匹配算法
数据结构·算法
INGNIGHT11 小时前
151 · 买卖股票的最佳时机 III(序列dp)
数据结构·算法·leetcode
Tisfy13 小时前
LeetCode 3644.排序排列:不对则与(脑筋急转弯)
数据结构·算法·leetcode·题解·位运算
H.莓飛15 小时前
【数据结构】快速排序专题
linux·服务器·c语言·数据结构·visual studio
重生之小比特15 小时前
【算法拾光】二分查找|在排序数组中查找元素的第一个和最后一个位置 + 搜索旋转排序数组
数据结构·算法·排序算法
YukiRinLL15 小时前
查找与排序算法:复杂度、稳定性
数据结构·算法·排序算法
careathers1 天前
【数据结构】从堆到 PriorityQueue:手写一个优先级队列
数据结构